【发布时间】:2021-11-10 04:23:40
【问题描述】:
一旦在泛型接口中使用“extends Explicit_value”,TS 的类型系统将变得“愚蠢”,即使代码“100% 正确”。
function fn<T extends "a" | "b">(param: T): T {
if (param === "a") return "a"/* <-- error
Type '"a"' is not assignable to type 'T'.
'"a"' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint '"a" | "b"'.
*/
else return "b"/* <-- error
Type '"b"' is not assignable to type 'T'.
'"b"' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint '"a" | "b"'.
*/
}
//that's ok:
function fn2<T extends string>(param: T): T {
return param
}
//even this:
function fn3<T extends "a">(): T {
return "a"/* <-- error
Type '"a"' is not assignable to type 'T'.
'"a"' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint '"a"'.
*/
}
【问题讨论】:
标签: typescript typescript-generics