【发布时间】:2021-11-24 14:38:51
【问题描述】:
我为每个函数写了三个相同类型的函数,让我们看看。
const func: <T extends string, K extends number = any>(arg: T) => K = () => {
return 1;
};
const anotherFunc = <T extends string, K extends number = any>(arg: T): K => {
return 1;
};
function someFunc<T extends string, K extends number = any>(arg: T): K {
return 1;
}
如您所见,我将K 定义为所有数字中的数字,以在每个数字中返回一个数字,但出现了一个奇怪的错误:
这是第一个函数:
Type '() => 1' is not assignable to type '<T extends string, K extends number = any>(arg: T) => K'.
Type 'number' is not assignable to type 'K'.
'number' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint 'number'.
这是最后两个函数:
Type 'number' is not assignable to type 'K'.
'number' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint 'number'
我认为这两个错误具有相同的意义。为什么 typescript 不能实现那种类型?
感谢您的帮助。
【问题讨论】:
标签: typescript typescript-generics