簡體   English   中英

為什么一種泛型函數不是泛型本身?

[英]Why is a type of generic function not generic itself?

考慮以下示例代碼:

interface so<T>
{
    a: T;
}

type test = <T>() => so<T>;

const so: test<number> = undefined;

哪個失敗

類型“ test”不是通用的

請解釋。

首先,這有點令人困惑,泛型基本上可以通過兩種方式來使用函數簽名。 它可以是作為函數的泛型類型,也可以是非泛型但代表泛型函數的類型。

例如:

type GenericTypeThatIsAFunction<T> = (o: T) => void
let functionThatIsNotGeneric: GenericTypeThatIsAFunction<number> // the generic type parameter is fixed
functionThatIsNotGeneric = (o: number) => { } // no generics here 
functionThatIsNotGeneric(1) // No generic here 


type TypeThatIsAGenericFunction = <T>(o: T) => void
let genericFunction: TypeThatIsAGenericFunction // the generic type is NOT fixed
genericFunction = <T>(o: T) => { } //  the implementation has to deal with any posible T
genericFunction(1) // T is not fixed to number for just this call 

在第一種情況下( GenericTypeThatIsAFunction ),您必須在聲明站點指定type參數,並將其永久固定到引用。 對引用的調用只能針對事先指定的類型進行。

在第二種情況( TypeThatIsAGenericFunction )中,除了在調用站點(否則會推斷出)之外,您無需指定type參數。 實現必須處理T任何可能值。

從通用函數簽名創建非通用函數簽名可能會很有用,但目前尚無語法可以支持此功能。 有一些討論允許這種行為,但是我無法說出它是針對近期最佳計划的(聲明者:不是編譯器團隊的成員,除了公共信息之外,我對他們的計划沒有任何見識)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM