TypeScript:将枚举值Map到实用工具中的枚举键

xdnvmnnf  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我有一个这种类型的枚举:

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中,我可以传递字符串值并获得相应的枚举键?

33qvvth1

33qvvth11#

不幸的是,字符串枚举没有TypeScript生成的反向Map,但是您仍然可以创建一个函数来查找与值匹配的枚举的键,如果不匹配,则抛出错误:

function asStateEnum(string: string): StateEnum {
    const key = Object.keys(StateEnum).find((key) => StateEnum[key as keyof typeof StateEnum] === string);

    if (!key) throw new TypeError(`'${string}' is not a member of StateEnum.`);

    return StateEnum[key as keyof typeof StateEnum];
}

然后在类中,可以使用此函数将字符串转换为枚举类型:

export class MyDTO {
    public state: StateEnum;

    constructor(infoFromApi: any) {
        const stateAsStringFromApi: string = infoFromApi.state;
        this.state = asStateEnum(stateAsStringFromApi);
    }
}

Playground

相关问题