我有這個功能
public getCollection<T>(collectionType: T): Collection<T> {
return new Collection<T>("some-arg1", "some-arg2")
}
在Collection
課堂上我有這個
export class Collection<T> {
public add (T item) {
// .. logic
}
}
我有一個這樣定義的用戶類
export class Student {
}
當我嘗試做
getCollection(Student).add(new Student());
有錯誤
TS2345:“Student”型別的引數不可分配給“typeof Student”型別的引數。'Student' 型別中缺少屬性'prototype',但在'typeof Student' 型別中是必需的。
以下作業正常。
new Collection<Student>().add( new Student());
那么當函式回傳泛型集合時有什么問題呢?
uj5u.com熱心網友回復:
T
實際上是 type typeof Student
。Student
是類的實體,typeof Student
而是建構式。要獲取建構式的實體型別,請使用直觀命名的InstanceType
內置函式:
public getCollection<T>(collectionType: T): Collection<InstanceType<T>> {
return new Collection<InstanceType<T>>("some-arg1", "some-arg2")
}
但是現在你必須添加一個不應該有太大問題的約束:
public getCollection<T extends new (...args: any[]) => any>(...
這應該導致:
public getCollection<T extends new (...args: any[]) => any>(collectionType: T): Collection<InstanceType<T>> {
return new Collection<InstanceType<T>>("some-arg1", "some-arg2")
}
uj5u.com熱心網友回復:
這個錯誤是由于泛型型別是從引數中推斷出來的;意思T
不是Student
,但實際上是typeof Student
。因此return new Collection<T>
,行為不像return new Collection<Student>
,而是相反return new Collection<typeof Student>
。
這可以通過實際為泛型引數分配一個型別來解決:
getCollection<Student>(Student)
以上使得引數的使用變得多余,因此getCollection
可以重構為以下內容:
getCollection<T>(): Collection<T> {
return new Collection<T>("some-arg1", "some-arg2");
}
并被稱為:
getCollection<Student>()
鏈接到操場。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470396.html
下一篇:使函式實體化其泛型引數