我正在尝试将我的应用程序迁移到 typescript 。我有一个基类,它是我的基础库对象。我的类根据基类创建。下面是我的问题的一瞥。
下面的代码可以工作,但自动完成功能不起作用。无法弄清楚应该为 Model
的类型定义什么。
const map = new WeakMap();
function weakRef<T>(context: T): T {
// @ts-ignore
if (!map.has(context)) { map.set(context, {}); }
// @ts-ignore
return map.get(context);
}
function getModel(provider: Provider) {
return class Model {
getSomething(key: string) {
return weakRef(provider).configuration(key);
}
};
}
class Provider {
configuration: (key: string) => string;
constructor() {
weakRef(this).configuration = (key: string) => {
return key;
};
weakRef(this).Model = getModel(this);
}
get Model(): any {
return weakRef(this).Model;
}
set Model(model: any) {
weakRef(this).Model = model;
}
}
const provider = new Provider();
const obj = new (provider.Model)();
console.log(obj.getSomething('test')); // This works, but autocomplete doesn't
我不想将提供程序传递给基本模型中的构造函数。 感谢任何帮助,谢谢。
最佳答案
您可以使用 ReturnType<T>
获取函数类型的返回类型.
在本例中,ReturnType<typeof getModel>
应该可以解决问题。
您还可以修复 //@ts-ignore
约束线T
是一个对象类型。
const map = new WeakMap();
function weakRef<T extends object>(context: T): T {
if (!map.has(context)) { map.set(context, {}); }
return map.get(context);
}
也就是说,我认为这个架构不必要地复杂。为什么不直接使用 this
而不是与 this
相关的值?
关于javascript - 如何在 Typescript 中以正确的方式动态创建类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55777390/