[英]Typescript generic type inference from default value
考慮以下函數。
public static convert<T, U>(t: T, conversion: ((toutput: T) => U) = ((t) => toutput)) {
return conversion(t);
}
Typescript 當前抱怨從轉換函數返回的 toutput 參數,這是默認參數。
我試圖讓 IDE 認識到,給定默認參數,T 與 U 相同。
我的用例如下:
convert(1) // returns 1
convert(1, x => ({x})) // returns an object with { x : 1 }
有沒有人知道讓編譯器靜音並能夠在上面正確創建此函數的方法?
我認為你可以通過重載來實現這一點:
public static function convert<T>(t: T): T;
public static function convert<T, U>(t: T, conversion: (t: T) => U): U;
public static function convert<T, U>(t: T, conversion?: (t: T) => U) {
return conversion ? conversion(t) : t;
}
..
const foo = convert(1) // inferred type 1
const bar = convert(1, x => ({x})) // inferred type { x : number }
1
被加寬為number
因為隱式文字類型在返回值的上下文中被加寬(例如x => ({x})
),這反過來導致T
推斷為number
。 您可以通過顯式鍵入第一個參數來避免這種情況:
const bar = convert(1 as 1, x => ({x})) // inferred type { x: 1 }
像這樣嘗試:
static convert<T, U = T>(t: T, conversion: ((toutput: T) => U) = t => t as T & U) {
return conversion(t);
}
const x = convert(1);
const y = convert(1, x => ({x}));
使用T
作為U
默認值,並將conversion
函數的默認值的返回類型conversion
為T & U
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.