Chart.js 4 + react-chartjs-2 TypeScript: 'The types of parsed.y are incompatible' / 'number | null is not assignable to number' in tooltip callbacks.label breaks next build
Building a Next.js 14 spending chart (react-chartjs-2 5.x, chart.js ^4.4) with an options object defined as a plain const and passed to <Bar options={options} />. next build ran "Linting and checking validity of types" and failed:
Type error: Type '{ responsive: boolean; plugins: { ... tooltip: { callbacks: { label: (context: { parsed: { y: number; }; }) => string; }; }; }; ... }' is not assignable to type '_DeepPartialObject<CoreChartOptions<"bar"> & ...>'. The types of 'plugins.tooltip.callbacks.label' are incompatible between these types. ... Type 'TooltipItem<"bar">' is not assignable to type '{ parsed: { y: number; }; }'. The types of 'parsed.y' are incompatible between these types. Type 'number | null' is not assignable to type 'number'.
Cause: in Chart.js 4 typings, cartesian parsed data extends Point, declared as { x: number | null; y: number | null } (dist/types/geometric.d.ts, checked in chart.js 4.6.1). Null is allowed because gaps (spanGaps, missing values) are valid data. A hand-written parameter type of { parsed: { y: number } } is therefore narrower than what Chart.js passes, and TypeScript rejects the options object. next dev does not type-check, so this typically shows up only in the container build.
Fix, either:
1. Use the library type and handle null:
import type { TooltipItem } from 'chart.js';
label: (ctx: TooltipItem<'bar'>) => Spending: ${formatCents((ctx.parsed.y ?? 0) * 100)}
2. Or type the whole options object so TypeScript infers callback params: const options: ChartOptions<'bar'> = { ... }. Then (ctx) needs no annotation at all.
A minimal local patch that also works: label(context: { parsed: { y: number | null } }) { const v = context.parsed.y ?? 0; ... }. For the y-axis tick callback, type value as number | string (Chart.js passes either), as in callback: (value: number | string) => '$' + value.toLocaleString(). Run npx tsc --noEmit locally before podman build to catch these in seconds instead of after npm install.