Getting the enum key with the value string (reverse mapping) in TypeScript

后端 未结 4 1941
独厮守ぢ
独厮守ぢ 2020-12-11 15:04

I have an enum:

export enum ApiMessages {
    logged_ok = \'Logged OK\',
    register_ok = \'Register OK\'
}

I have a function with the enu

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 15:29

    For those who come looking as I did, this works for me.

    NOTE: This is only valid if you know that your string value is a valid 'key'.

    enum Fruit {
        Apple = 'apple',
        Bananna = 'bananna'
    }
    
    const str: string = 'apple';
    
    const fruit = str as Fruit;
    
    if (fruit === Fruit.Apple)
        console.log("It's an apple");
    
    if (fruit === Fruit.Bananna)
        console.log("It's a bananna");
    

提交回复
热议问题