[英]How to specialize template type of a generic class in typescript?
是否可以在typescript
中的泛型函數中專門化泛型類的模板類型?
假設我有一個通用接口和一個將接口構造函數作為參數的函數:
interface IA<T> {
func(arg: T)
}
function g<T, IAType extends IA<T>>(
constructor: { new(): IAType }
): (arg: T) => IAType {
const ins = new constructor();
return arg => {
ins.func(arg);
return ins;
}
}
然后我提供了類實現IA<T>
,即
class A implements IA<{ key: string }> {
func(arg: { key: string }) {
console.log(arg.key);
}
}
const t = g(A); // type of t is (arg: {}) => A
如何編寫函數g
或類A
以使函數g
由於傳遞了參數而可以專用於正確的模板類型? 我想最后的t
具有類型(arg: {key: string}) => A
此類型為g
constructor
參數
constructor: { new(): IAType }
並沒有真正施加約束, IAType
中的func()
必須以T
作為其參數類型。 唯一的約束是IAType extends IA<T>
,這意味着IAType
中的func
可以具有任何類型,只要它與func(arg: T)
兼容即可。 推論算法可能以最小類型{}
開頭,驗證func(arg: {})
與func(arg: T)
兼容並止於此。
對constructor
類型更加嚴格有助於:
interface IA<T> {
func(arg: T): void
}
function g<T, IAType extends IA<T>>(
constructor: { new(): IA<T> & IAType }
): (arg: T) => IAType {
const ins = new constructor();
return arg => {
ins.func(arg);
return ins;
}
}
class A implements IA<{ key: string }> {
func(arg: { key: string }) {
console.log(arg.key);
}
}
const t = g(A); // type of t is (arg: { key: string; }) => A
IA<T> & IAType
都是必需的。 如果只有IA<T>
,則將根據需要推斷arg
類型,但是返回類型將僅為IA<T>
,而不是A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.