[英]TypeScript Generics: Function that returns constructor of instance specified as parameter
我正在學習 TypeScript。 我一直在思考 generics,但遇到了一個小問題,我正在努力尋找答案。
我用谷歌搜索了很多很多搜索查詢,但是由於搜索詞的模糊性,以及對某些語言結構的技術名稱缺乏了解,我得到了很多噪音。
我在 TypeScript 的網站上閱讀了三個相關的文檔頁面,但找不到我需要的信息。 也許我忽略了一些東西,如果是這樣的話,一個好的解釋的鏈接將不勝感激。
我想編寫一個 function ,它返回指定為保留類型的參數的實例的構造函數,因為 TypeScript 中的 this.constructor 不是 ZA2F2ED4F8EBC2CBB4C21A29DZ40AB6 的類型
非常清楚,我知道我可以做到這一點:
const aa2 = (a.constructor as typeof A).make();
這是一個精簡的案例:
class A {
prop1: string;
prop2: number;
constructor(prop1: string, prop2: number) {
this.prop1 = prop1;
this.prop2 = prop2;
}
method() {
}
static make() {
return new this('test', 42);
}
}
function constructor<T>(instance: T): { new(...args): T } {
return instance.constructor as { new(...args): T };
}
const a = A.make();
// Property 'make' does not exist on type 'new(...args: any[]) => A'
const aa = constructor(a).make();
// This works, but is not pretty
const aa2 = (a.constructor as typeof A).make();
它需要在任何 class 上工作,無論是否帶有構造函數參數。
我可以做相反的事情:
export function make<T>(type: { new(...args): T }, ...args): T {
return new type(...args);
}
make(A, 'test', 42).method();
似乎我沒有得到一些關鍵因素。 如果您能准確地發現我的想法出錯的地方,我歡迎對我的誤解做出很好的解釋。
無法從實例類型移動到 class 類型。 這只有在constructor
被鍵入為 class 類型時才有可能(它不是)有一個開放的票可以實現這一點,但它已經開放並討論了很長時間。
如果您控制客戶端類,則可以將成員添加到 class 以使該方法正常工作:
class TraceableClass<TThis> {
private typedConstructor!: TThis
}
class A<TThisClas = typeof A> extends TraceableClass<TThisClas>{
prop1: string;
prop2: number;
constructor(prop1: string, prop2: number) {
super();
this.prop1 = prop1;
this.prop2 = prop2;
}
method() {
}
static make() {
return new this('test', 42);
}
}
function constructor<T>(instance: TraceableClass<T>): T {
return instance.constructor as any as T;
}
const a = A.make();
// Ok now
const aa = constructor(a).make();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.