我有這個功能
function getCollection<T>(collectionType: T): Collection<T> {
return new Collection<T>()
}
在Collection課堂上我有這個
export class Collection<T> {
public add (item: T) {
// .. logic
}
}
我有一個這樣定義的用戶界面
export interface IStudent {
}
當我嘗試做
getCollection(IStudent).add({});
有錯誤
TS2693:“IStudent”僅指一種型別,但在此處用作值。
如何讓它接受泛型型別并回傳嚴格型別的集合?
uj5u.com熱心網友回復:
泛型型別是型別引數,而不是函式引數。你定義
function getCollection<T>(): Collection<T> {
return new Collection<T>()
}
(注意collectionType無論如何都是一個未使用的引數),然后將其稱為
getCollection<IStudent>().add({});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476203.html
標籤:javascript 打字稿
