← 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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
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.
- types
type _ = Expect<Equal<Shape["kind"], "circle" | "rect" | "square">>;
- types
area({ kind: "square", size: 3 });
- types
// @ts-expect-error - a circle has a radius, not a width area({ kind: "circle", width: 2 });
expect(Math.abs(area({ kind: 'circle', radius: 2 }) - Math.PI * 4) < 1e-9).toBe(true);
expect(area({ kind: 'rect', width: 3, height: 4 })).toBe(12);
expect(area({ kind: 'square', size: 5 })).toBe(25);