避免在TypeScript数组构造中重复方法调用

时间:2019-03-21 16:14:00

标签: typescript enums

我有一个带有数百个值的TypeScript枚举

export enum ObjectTypes {
    OBJ_TYPE_1 = 1,
    OBJ_TYPE_2 = 2,
    OBJ_TYPE_3 = 3,
    OBJ_TYPE_4 = 4,
    OBJ_TYPE_5 = 5,
    OBJ_TYPE_5 = 6,
    ...
    OBJ_TYPE_500 = 500,
}

应用程序中的几个地方构造了数组

private static ALLOWED_OBJ_TYPES: string[] = [
    ObjectTypes.OBJ_TYPE_1.toString(),
    ObjectTypes.OBJ_TYPE_3.toString(),
    ObjectTypes.OBJ_TYPE_6.toString(),
...
];

是否有更短的更优雅的方法来声明这些数组,从而避免重复ObjectTypes..toString()

请注意,每个数组的枚举值集会任意变化。

1 个答案:

答案 0 :(得分:2)

这将避免几次击键,并且仍然是安全的类型,不确定是否一定要更优雅,但是情人眼中的情人眼神:)

export enum ObjectTypes {
    OBJ_TYPE_1 = 1,
    OBJ_TYPE_2 = 2,
    OBJ_TYPE_3 = 3,
    OBJ_TYPE_4 = 4,
    OBJ_TYPE_5 = 5,
    OBJ_TYPE_5 = 6,
    OBJ_TYPE_500 = 500,
}

function createEnumArray<T>(e: T, ...keys: Array<keyof T>) {
    return keys.map(k => e[k].toString())
}

let ALLOWED_OBJ_TYPES: string[] = createEnumArray(ObjectTypes, 
    "OBJ_TYPE_1",
    "OBJ_TYPE_3",
    "OBJ_TYPE_6",
);