简体   繁体   中英

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. The code above works, and tsc will not throw any error. However in my vscode, it tell me something wrong.

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

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 )

Another option, would be to not index by a generic string but rather by a string that is a key for 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]();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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