打字稿动态访问属性

时间:2018-01-24 08:05:06

标签: typescript

这是一个演示:

class Vec2 {};
class Vec3 {};
class Vec4 {};

let mylibs = {
    Vec2: Vec2,
    Vec3: Vec3,
    Vec4: Vec4
};
let len = Math.round(Math.random() * 2) + 2;
let VecType = 'Vec' + len;
let randomVector = new mylibs[VecType]();

我想通过用户输入创建一些东西,VecType是我用来模拟用户输入的东西。 上面的代码有效,tsc不会抛出任何错误。但是在我的vscode中,它告诉我一些错误。

enter image description here enter image description here

我想解决这种错误。感谢。

1 个答案:

答案 0 :(得分:2)

由于错误表明一种解决方案是在类型中添加索引签名,以便允许通过任何字符串进行索引:

let mylibs : { [key: string]:  new () => any} = {
    Vec2: Vec2,
    Vec3: Vec3,
    Vec4: Vec4
};

如果您想要更具限制性,则可以使用Vec*类型的基类,或所有属性类型的联合类型(Vec2|Vec3|Vec4

另一种选择是,不是通过通用字符串索引,而是通过作为mylibs的键的字符串来索引。动态构造这样的字符串将涉及一个不太特别安全的演员:

let VecType: keyof typeof mylibs = ('Vec' + len) as any;
let randomVector = new mylibs[VecType]();