简体   繁体   English

TypeScript使用枚举集的一部分来定义变量的类型

[英]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; A. align: Alignment.Left | Alignment.Top; align: Alignment.Left | Alignment.Top;

B. creating new enum for this task like B.为此任务创建新的枚举

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. 这意味着选项A是有效的,因为您可以利用联合枚举来实现所需的功能。

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,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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