← All tasksTypeScript · Junior

Discriminated union: shape area

The Shape type describes a circle and a rectangle; the kind field tells which one it is. Add a square { kind: "square"; size: number } to it and write area(shape) that returns the area of any shape.

It helps if TypeScript reminds you about area when another shape is added one day: add an exhaustiveness check with never.

Tests (6)

Type tests are checked by the TypeScript compiler in strict mode. Expect<Equal<A, B>> passes when the types match exactly, and // @ts-expect-error passes when the next line does not compile. The first run downloads the compiler, so it takes a few seconds.

  1. types
    type _ = Expect<Equal<Shape["kind"], "circle" | "rect" | "square">>;
  2. types
    area({ kind: "square", size: 3 });
  3. types
    // @ts-expect-error - a circle has a radius, not a width
    area({ kind: "circle", width: 2 });
  4. expect(Math.abs(area({ kind: 'circle', radius: 2 }) - Math.PI * 4) < 1e-9).toBe(true);
  5. expect(area({ kind: 'rect', width: 3, height: 4 })).toBe(12);
  6. expect(area({ kind: 'square', size: 5 })).toBe(25);