简体   繁体   English

如何使用 typescript 接口作为枚举?

[英]how to use a typescript interface as an enum?

I'm working with a library proto file that generates an interface , that should be able to be used as an enum:我正在使用一个生成 interface库 proto 文件,它应该能够用作枚举:

export interface FinishReasonMap {
  NULL: 0;
  LENGTH: 1;
  STOP: 2;
  ERROR: 3;
  FILTER: 4;
}

The types are auto-generated from a.proto definition, so its hard to update them to be a basic enum.这些类型是从 a.proto 定义自动生成的,因此很难将它们更新为基本枚举。

now, I can use that in my own type def like:现在,我可以在我自己的type def 中使用它,例如:

export type ImageObject = {
  finishReason?: FinishReasonMap[keyof FinishReasonMap];
}

but I'm not able to use it for a comparison, eg:但我无法使用它进行比较,例如:

if (item.finishReason === FinishReasonMap.FILTER) {...

error: 'FinishReasonMap' only refers to a type, but is being used as a value here.错误:“FinishReasonMap”仅指一种类型,但在此处用作值。

I know TS enum's are a bit funky sometimes, but not clear how to use this.我知道 TS 枚举有时有点时髦,但不清楚如何使用它。 I think I want something like the opposite of typeof to get enum values from the interface?我想我想要与typeof相反的东西从接口获取枚举值?

TS is pretty much in the right here. TS几乎就在这里。

You are using an interface there so the syntax NULL:0 doesn't specify that NULL has value 0 , but that the type of NULL is 0 .您在那里使用interface ,因此语法NULL:0没有指定NULL的值为0 ,但NULL的类型为0 This, in the end, will force anyone implementing the interface to assign 0 to NULL .最后,这将迫使任何实现该接口的人将0分配给NULL

You can see this in action here:你可以在这里看到这个:

export interface FinishReasonMap {
  NULL: 0;
  LENGTH: 1;
  STOP: 2;
  ERROR: 3;
  FILTER: 4;
}

export class FinishReasonMapT implements FinishReasonMap {
    NULL:0 = 0;
    LENGTH:1 = 1;
    STOP:2 = 2;
    ERROR:3 = 3;
    FILTER:4 = 4;
}

The bottom line is that when you're trying to do FinishReasonMap.FILTER you are trying to access a type (interface) and that doesn't work at runtime.底线是,当您尝试执行FinishReasonMap.FILTER时,您正在尝试访问一个类型(接口),而这在运行时不起作用。

I don't know of any way of converting that interface to a runtime value that you can use.我不知道有什么方法可以将该接口转换为您可以使用的运行时值。

Your most likely course of action is to change the generated code to either an enum of an const object .您最可能的做法是将生成的代码更改为const objectenum

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

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