2016-11-11 99 views
0

委託我不能得到這個簡單的代碼片段在打字稿編譯(1.8)分配泛型函數打字稿

function test<T>(a: string, input: T): T { 
    return input 
} 

const xyz: (a: string, b: number) => number = test<number> 

我有一個函數,它接受一個委託,但泛型函數轉換成代表格式要求我執行這個額外的步驟:

const xyz: (a: string, b: number) => number = (a,b) => test<number>(a,b) 

......這對我來說似乎並不理想。任何想法,爲什麼這不起作用,或者如果有另一種語法來實現相同?

回答

1

你不需要通用約束可言,這將做到:

const xyz: (a: string, b: number) => number = test; 

code in playground

編譯器推斷通用約束是基於您明確定義的類型數量變量。
另一種方式來做到這一點是:

const xyz = test as (a: string, b: number) => number; 

code in playground

+0

你是對的!在這種情況下,我仍然覺得你不能使用類型約束有些尷尬。 –

+0

好吧,編譯器不喜歡'let a = test '的語法,只有在調用函數時才應該使用泛型約束。 –