在這個例子中:
type MyType = 'val1' | 'val2' | 'val3';
const variable = 'val1' as MyType;
const val2 = 'val2';
const val3 = 'val3';
declare function test<U extends MyType>(...args: U[]): void;
test(val2, val3); // U successfully resolves to "val3" | "val2"
declare function test2<T, U extends T>(value: T | undefined, ...values: U[]): void;
test2(variable, val2, val3); // U gets widened to "val1" | "val2" | "val3"
在test和 中test2,U extends MyType。
然后,我希望test2以決心U來"val3" | "val2",就像它在做test,但事實并非如此。
這是為什么?
打字稿游樂場
uj5u.com熱心網友回復:
我相信這是型別系統偷工減料的一個例子。允許 Typescript 時不時地在型別檢查上偷工減料。特別是如果它可以檢測到結果型別不會在型別系統的其他地方使用。我認為打字稿認為該型別"val1" | "val2" | "val3"對于引數串列來說已經足夠好了。但是,假設我們將test2from的回傳型別更改void為U。然后,由于U預計型別將被回傳并可能在打字稿的其他地方使用,編譯器將需要花更多時間來決議U.
type MyType = 'val1' | 'val2' | 'val3';
const variable = 'val1' as MyType;
const val2 = 'val2';
const val3 = 'val3';
declare function test2<T, U extends T>(value: T | undefined, ...values: U[]): void;
test2(variable, val2, val3); // U gets widened to "val1" | "val2" | "val3"
declare function test3<T, U extends T>(value: T | undefined, ...values: U[]): U;
test3(variable, val2, val3); // U successfully resolves to "val3" | "val2"
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/373480.html
