我认为这是一个类型系统偷工减料的例子。Typescript被允许时不时地在类型检查上走捷径。尤其是如果它能够检测到生成的类型不会在类型系统的其他地方使用。我想typescript确认了
"val1" | "val2" | "val3"
对于参数列表来说已经足够好了。
然而,假设我们改变了
test2
从…起
void
到
U
.然后,因为
U
预计将返回并可能在typescript中的其他地方使用,编译器将需要花费更多时间来解析实际/最窄的类型
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"
playground