Typescript 如何向TypesScript类添加动态属性并维护正确的键入
我有一个Typescript 如何向TypesScript类添加动态属性并维护正确的键入,typescript,typescript-typings,typescript2.0,Typescript,Typescript Typings,Typescript2.0,我有一个Users类,我正在从文件Users.ts 导出默认类用户{} 然后我从另一个文件导出Users.ts,index.ts: //类 从“./Users”导出{default as Users} 我有第三个文件,Foo.ts,我想在其中动态实例化从index.ts导出的所有类,并将它们作为属性添加到该类中: import*作为类从“./index”导入 福班{ 构造函数(){ const httpClient=新的httpClient() } _addClasses(){ for(类中
Users
类,我正在从文件Users.ts
导出默认类用户{}
然后我从另一个文件导出Users.ts
,index.ts
:
//类
从“./Users”导出{default as Users}
我有第三个文件,Foo.ts
,我想在其中动态实例化从index.ts
导出的所有类,并将它们作为属性添加到该类中:
import*作为类从“./index”导入
福班{
构造函数(){
const httpClient=新的httpClient()
}
_addClasses(){
for(类中常量类){
this[class]=新类[class](this.httpClient);
}
}
}
我的问题是,如何将正确的类型添加到Foo
,以便在IDE中为获得正确的自动完成。用户
如:
newfoo(newhttpclient)。用户
这个问题的第一部分是创建一个包含导入模块的实例类型的新类型。为此,我们将使用预定义的条件类型InstanceType
来提取类的实例类型。要获得模块的类型,我们将使用typeofclass
。将其全部封装在映射类型中,我们可以得到:
type ClassInstances = {
[P in keyof typeof classes]: InstanceType<typeof classes[P]>
}
// For the example above this is equivalent to
type ClassInstances = {
Users: classes.Users;
}
我在任何地方都看不到属性
.users
的任何定义,除非您尝试使用它。而且你的Foo
构造函数没有任何参数。没错,我想推断类型。可能是@Nit的重复。你是正确的,但我希望避免创建包装函数+类型强制。
import * as classes from './index';
type ClassInstances = {
[P in keyof typeof classes]: InstanceType<typeof classes[P]>
}
class Foo extends (class {} as new () => ClassInstances) {
httpClient: HttpClient;
constructor() {
super();
this.httpClient = new HttpClient()
this._addClasses();
}
_addClasses() {
for (const cls of Object.keys(classes) as Array<keyof typeof classes>) {
this[cls] = new classes[cls](this.httpClient);
}
}
}
new Foo().Users // ok now name is the same as the name used in the export in index.ts so it's upper case. No string manipulation on string properties.