Skip to content

TypeScript - Union Type Definition and Usage

What is Union Type?

A Union Type is a combination of two or more types.

For example, if there are multiple data types,

ts
interface Square {
  kind: 'square'
  size: number
}
interface Rectangle {
  kind: 'rectangle'
  width: number
  height: number
}
interface Circle {
  kind: 'circle'
  radius: number
}

The Union Type is defined as follows:|

ts
type Shape = Square | Rectangle | Circle

Type Inference for Union Types

In TypeScript, the Type Inference to deduce each type. When checking TypeScript, use the TypeScript Playground You can check it out online.

ts
const getArea = (shape: Shape) => {
  if (shape.kind === "square") {
    // If you use the properties of Rectangle
    // and Circle here, a type error occurs.
    return shape.size * shape.size;
  }
  // The rest is ommited
}