State, and the Four States Again

State is usually inferred. useState(0) is a number and needs nothing.

Annotate when the initial value is not representative, which in practice means null: useState<Book | null>(null) , because useState(null) infers null and nothing else, and every later setBook(realBook) is then an error.

And here the course closes a loop. The four states from the React course, the reducer from module 12 of that course, and the discriminated union from module 6 of this one are all the same idea arriving from three directions.

With a discriminated union, loading carrying an error message is not a bug you avoid. It is a value that cannot be constructed.

Try it

Add a fifth state to Result and watch the switch fail until you handle it.

loading editor…

checking…

The last line will not compile. Neither will removing any case from the switch. That is the whole argument for this course in eighteen lines.

◈ Graded Types

Define a Book type with id (string), title (string) and year (number or null). Define CardProps with a book (Book), an onSelect callback taking a string id and returning nothing, and an optional compact flag. Then write label(p: CardProps): string returning the title alone when compact is true, and "Title (year)" otherwise, using "unknown" in place of a null year.

Checked against the compiler, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…
real tsc, strict mode

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back