Union types and narrowing in TypeScript
Handle values that can be one of several types. Press Run to try it, then change the code and run it again.
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
console.log(area({ kind: 'circle', radius: 2 }).toFixed(2));
console.log(area({ kind: 'rectangle', width: 3, height: 4 }));
Output
Press Run to see the output.
More TypeScript examples
- Hello, World · Print a line of text with a typed variable.
- Interfaces and objects · Describe the shape of an object and use it in a function.
- Generics · Write one function that works with any type, safely.
- Catch a type error · See how TypeScript stops a bug before the code runs.
- Async and await · Wait for promises with typed results.