我有一个这种类型的枚举:
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
“正在运行”。
在我的 DTO 模型中
MyDTO
我想将它公开为 StateEnum 这样接收 DTO 的任何人都可以像这样检查不同的状态:
case (dtoObj.state) {
switch StateEnum.RUNNING: // do something
switch StateEnum.STOPPED: // do something else
}
如何实现 TypeScript 枚举的反向映射,我可以传递字符串值并获得相应的枚举键?