简体   繁体   中英

TypeScript using part of enum set to define type of variable

I have enum that looks like this

export enum Alignment {
  Top = 'top',
  Right = 'right',
  Bottom = 'bottom',
  Left = 'left',
}

Commonly I will use it in defining interface for eg react component props like

interface CompProps {
  align: Alignment;
}

But now wonder if I can use only the part of this enum, like

interface CompProps {
  align: `part of Alignment: left and top`;
}

Is there a common pattern for this?

I may think of:

A. align: Alignment.Left | Alignment.Top; align: Alignment.Left | Alignment.Top;

B. creating new enum for this task like

enum CompAlignment {
  Top = Alignment.Top,
  Left = Alignment.Left,
}

According to typescript docs :

When all members in an enum have literal enum values, some special semantics come to play.

The first is that enum members also become types as well! For example, we can say that certain members can only have the value of an enum member.

This means option A is valid as you can leverage union enums to achieve what you are looking for.

enum ShapeKind {
    Circle,
    Square,
}

interface Circle {
    kind: ShapeKind.Circle;
    radius: number;
}

interface Square {
    kind: ShapeKind.Square;
    sideLength: number;
}

let c: Circle = {
    kind: ShapeKind.Square,
    //    ~~~~~~~~~~~~~~~~ Error!
    radius: 100,
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM