ayumitamai97
ayumitamai97

Reputation: 11

TypeScript: Getting names (as string) of Union's possible types?

Is it possible to get names of Union's possible types?

Given that I have defined these interfaces and type aliases:

// https://basarat.gitbook.io/typescript/type-system/discriminated-unions

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

Can I get a union of string like this?

type ShapeName = 'Square' | 'Rectangle';

Upvotes: 1

Views: 366

Answers (1)

You can do smth like that:

interface Square {
  kind: "square";
  size: number;
}

interface Rectangle {
  kind: "rectangle";
  width: number;
  height: number;
}

type Shape = Square | Rectangle;

type ShapeName = Shape['kind'] // 'square' | 'rectangle';

Please keep in mind, you are unable to obtain interface name unless you map some how it.

Upvotes: 2

Related Questions