从打字稿中的字符串和值解析枚举

时间:2019-01-04 18:00:09

标签: typescript enums

我有一个基本的errorCode枚举,例如

export enum SomeErrorCodes {
    none = 0,
    notFound = 1,
    duplicated = 2
}

我从webAPI收到枚举的名称,它是字符串“ SomeErrorCodes”和一个数字,比如说1。如何将它们解析为打字稿中的SomeErrorCodes.notFound

谢谢

2 个答案:

答案 0 :(得分:1)

您的枚举将被转换为

Object
0: "none"
1: "notFound"
2: "duplicated"
duplicated: 2
none: 0
notFound: 1

因此您可以轻松地通过键获取值,

function getErrorCode(code: number): string {
  return SomeErrorCodes[code] || 'Code not exist';
}

答案 1 :(得分:0)

您可以使用Object.keys获取密钥名称,然后使用该名称获取适当的枚举。该代码将在https://www.typescriptlang.org/play/index.html上运行,并应给您足够的资源来完成它:

enum Fruits {
    Apple = 1,
    Orange
}

enum Vegetables {
    Carrot = 75,
    Lettuce = 88,
    Asparagus = 96
}

class ThingParser {
    public GetArbitraryValues(fromObject: any): string[] {
        const fancyStrings: string[] = [];
        const key = Object.keys(fromObject)[0];

        let getStringMethod: (theValue: number) => string;

        switch (key) {
            case "Fruits":
                getStringMethod = (fruit: number) => {
                    return Fruits[fruit];
                }
                break;
            case "Vegetables":
                getStringMethod = (veg: number) => {
                    return Vegetables[veg];
                }
                break;
            default:
                throw "Unknown enum...";
        }

        const intValues = (<string>fromObject[key]).split(",")
            .map(x => Number.parseInt(x.trim()));


        for (const intVal of intValues) {
            fancyStrings.push(getStringMethod(intVal));
        }

        return fancyStrings;
    }
}

const parser = new ThingParser();
let fruits = document.createElement('h2');
fruits.textContent = parser.GetArbitraryValues({ "Fruits": "1,2" }).join(", ");
document.body.appendChild(fruits);
let veggies = document.createElement('h2');
veggies.textContent = parser.GetArbitraryValues({ "Vegetables": "88" }).join(", ");
document.body.appendChild(veggies);