TypeScript:为类构造函数创建函数包装器



我正在尝试创建一个函数,该函数接受一个类并返回可以返回类实例的函数。但是,它仅提供基类的类型信息,并且在我尝试createFactory函数中创建实例时出错。操场

class BaseStore {
public id = 1;
}
class OneStore extends BaseStore {
public action() { }
constructor(public a: string, public b: number) {
super()
}
}
function createFactory<T extends BaseStore, C extends new (...args: any) => T>(Create: C) {
return (...args: ConstructorParameters<C>) => new Create(...args);
}
const oneFactory = createFactory(OneStore);
const one = oneFactory('s', 2);
one.id
one.action();

Typescript 无法真正解析仍包含未解析类型参数的条件类型。你可以用不同的方式编写类型:

function createFactory<T extends BaseStore, P extends any[]>(Create: new (...args: P) => T) {
return (...args: P) => new Create(...args);
}

游乐场链接

最新更新