O'Reilly logo

TypeScript Blueprints by Ivo Gabe de Wolff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating tagged union types

With TypeScript 2.0, you can add a tag to union types and use these as type guards. That feature is called: discriminated union types. This sounds very difficult, but in practice it is very easy. The following example demonstrates it:

interface Circle { 
  type: "circle"; 
radius: number; 
} 
interface Square { 
  type: "square"; 
  size: number; 
} 
type Shape = Circle | Square; 
function area(shape: Shape) { 
  if (shape.type === "circle") { 
    return shape.radius * shape.radius * Math.PI; 
  } else { 
    return shape.size * shape.size; 
  } 
} 

The condition in the if statements works as a type guard. It narrows the type of shape to circle in the true branch and square in the false branch.

To use this feature, you must create a union type of which ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required