Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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';
question from:https://stackoverflow.com/questions/65886571/typescript-getting-names-as-string-of-unions-possible-types

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...