Learning
TypeScript

Union és intersection típusok

Union (|), narrowing, discriminated union, és intersection (&) példákkal.

Union típus (|)

let id: string | number
id = "abc-123"
id = 42

Narrowing

function formatId(id: string | number): string {
  if (typeof id === "string") return id.toUpperCase()
  return id.toFixed(0)
}

Discriminated union

type Circle = { kind: "circle"; radius: number }
type Rectangle = { kind: "rectangle"; width: number; height: number }
type Shape = Circle | Rectangle

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2
    case "rectangle":
      return shape.width * shape.height
  }
}

Intersection típus (&)

type WithTimestamps = { createdAt: Date; updatedAt: Date }
type User = { id: number; name: string }

type UserWithTimestamps = User & WithTimestamps

On this page