TypeScriptLesson 13 of 16

Discriminated unions

A discriminated union is a set of object types that share a tag field such as kind or status. From the tag, TypeScript knows which other fields the object has.

Key points

  • The tag is a literal field that differs per member: kind: "circle".
  • A switch over the tag narrows the object in every case.
  • In default, assign the value to a never variable: that is the exhaustiveness check.
  • Add a new member and forget its case, and the compiler shows an error.

Example

type Shape =  | { kind: "circle"; radius: number }  | { kind: "square"; side: number }; function area(shape: Shape): number {  switch (shape.kind) {    case "circle":      return Math.PI * shape.radius ** 2; // shape is the circle here    case "square":      return shape.side ** 2; // and the square here    default: {      // if a new kind is added to Shape and not handled, this line turns red      const unreachable: never = shape;      return unreachable;    }  }} console.log(area({ kind: "square", side: 3 }));console.log(area({ kind: "circle", radius: 1 }).toFixed(2));

radius is available in case "circle", side in case "square". Add a triangle to Shape and the never line turns red at once.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Add an error member with a message field to RequestState, handle it in render, add a default with a never check and put the error state in the array. The last output line is "Error: Not found".

Output

What your program prints appears here.