具有已知属性的Typescript对象动态

时间:2018-07-31 21:53:55

标签: typescript

我遇到需要动态使用对象属性的情况。我不喜欢打字稿。.

情况与上述情况类似。

如何键入检查Enum[val]foo变量?

enum Enum {
    VAR1 = "A",
    VAR2 = "B",
}

const foo = ["VAR1", "VAR2"];
foo.forEach(val => {
    const a = Enum[val]; // Typescript doesn't like it (val implicitly has 'any' type...)
    const b = Enum[val as any]; // This is "OK", but I use "any", which I'm trying to avoid.
});

1 个答案:

答案 0 :(得分:3)

const foo: (keyof typeof Enum)[] = ["VAR1", "VAR2"];