[英]What is the TypeScript type of an enum
I am wondering what is the type of an enum?我想知道枚举的类型是什么? In my example I need to reference my
Direction
enum in my template.在我的示例中,我需要在模板中引用我的
Direction
枚举。 I am doing this by assigning the Direction
enum to the direction
variable I have exposed in my component.我通过将
Direction
枚举分配给我在组件中公开的direction
变量来做到这一点。 This variable is currently type any
but I want to be more specific.这个变量目前是
any
类型,但我想更具体一点。 What should this type be?这种类型应该是什么?
<!-- component.html -->
<p [ngSwitch="getDirection()"]>
<span *ngSwitchCase="direction.NORTH">Heading North</span>
<span *ngSwitchCase="direction.EAST">Heading East</span>
</p>
// component.ts
enum Direction {
NORTH,
EAST,
SOUTH,
WEST
}
direction: any; // <-- what should this type be?
constructor() {
this.direction = Direction;
}
direction$: typeof Direction;
Should be ok.应该可以。
But actually you do not need this.但实际上你不需要这个。 You may let typescript to infer this type:
您可以让 typescript 来推断这种类型:
enum Direction { NORTH, EAST, SOUTH, WEST }
class MyComponent {
readonly direction$ = Direction;
constructor() {
//...
}
}
There is no need to wait with initialization until constructor is called in this case, as everything is known in advance.在这种情况下,无需等待初始化,直到调用构造函数,因为一切都是预先知道的。
Now, you may hover direction$ field and see it's inferred type (I assume you are using vscode).现在,您可以 hover direction$ 字段并查看它的推断类型(我假设您使用的是 vscode)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.