Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.6 — TypeScript for Charts
Data Visualization · Example 1 of 2

Typed rows, a typed scale and a generic Bars component

The compiler is satisfied: the Types panel is empty. T was inferred as DayRow from data, so d.date and d.rides are checked. The last line shows the all-equal case: a zero-width domain gives the middle of the range (50) and not NaN.

Type the rows a chart reads, the scales it builds and the props it takes. The compiler then catches a misspelt field, a missing value and the wrong kind of scale before the page ever runs, at the price of a few annotations.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a generic Dots<T> props type for a scatter chart: rows T[], accessors x and y returning numbers, and id returning a string. Then call it with { minutes: number; km: number; id: string } rows.

02

Write extentOr(values: number[], fallback: [number, number]): [number, number] and say why it helps a scale.

Explain it without notes

01

Why is the row type the most useful type in chart code?

02

What does d3.max(rows, (d) => d.rides) return for an empty list, and how does strict mode make you handle it?

03

Why can a ScaleLinear not be passed where a ScaleTime is expected?

04

What does a type assertion (as) do, and why is it dangerous for data from a CSV?

Typed rows, a typed scale and a generic Bars component

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

bars: 2
156.71092184368737 50