我有一个这种类型的枚举:
export enum StateEnum {
STARTING = 'starting',
RUNNING = 'running',
STOPPING = 'stopping',
STOPPED = 'stopped',
DELETING = 'deleting',
}
我有一个这样的DTO对象:
export class MyDTO {
public state: StateEnum;
constructor(infoFromApi: any) {
const stateAsStringFromApi: string = infoFromApi.state;
this.state = // Here I am looking for a way to map the stateAsStringFromApi of type string into the corresponding key in the StateEnum.
}
}
例如:
比如说,从API中,我得到的是infoFromApi.state
作为"running"。
在我的DTO模型MyDTO
中,我希望将其公开为StateEnum,以便接收DTO的任何人都可以检查不同的状态,如下所示:
case (dtoObj.state) {
switch StateEnum.RUNNING: // do something
switch StateEnum.STOPPED: // do something else
}
如何实现TypeScript枚举的反向Map,在此Map中,我可以传递字符串值并获得相应的枚举键?
1条答案
按热度按时间33qvvth11#
不幸的是,字符串枚举没有TypeScript生成的反向Map,但是您仍然可以创建一个函数来查找与值匹配的枚举的键,如果不匹配,则抛出错误:
然后在类中,可以使用此函数将字符串转换为枚举类型:
Playground