这是一个演示:
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中,它告诉我一些错误。
我想解决这种错误。感谢。
答案 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]();