简体   繁体   English

Typescript动态访问属性

[英]Typescript dynamic access property

Here is a demo: 这是一个演示:

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]();

I want to create something by user input, the VecType is something I used to simulate user input. 我想通过用户输入创建一些东西, VecType是我用来模拟用户输入的东西。 The code above works, and tsc will not throw any error. 上面的代码有效,并且tsc不会引发任何错误。 However in my vscode, it tell me something wrong. 但是在我的vscode中,它告诉我一些错误。

在此处输入图片说明 在此处输入图片说明

I want to resolve this kind of error. 我想解决这种错误。 Thanks. 谢谢。

As the error suggests one solution would be to add an index signature to the type so as to allow indexing by any string : 正如错误所暗示的,一种解决方案是在类型中添加索引签名,以便允许按任何字符串进行索引:

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

Instead of any if you want to be more restrictive, you could use a base class of the Vec* types, or a union type of all property types ( Vec2|Vec3|Vec4 ) 如果要限制更严格,可以使用Vec*类型的基类或所有属性类型的联合类型( Vec2|Vec3|Vec4Vec2|Vec3|Vec4任何其他类型。

Another option, would be to not index by a generic string but rather by a string that is a key for mylibs . 另一种选择是,不按通用字符串索引,而是按mylibs键的字符串mylibs To construct such a string dynamically would involve a cast which would not be particularly safe: 动态构造这样的字符串将涉及强制转换,但并不特别安全:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM