【发布时间】:2022-09-29 21:37:56
【问题描述】:
我不明白为什么有时打字稿无法推断出 const 的泛型类型。
这是一个例子:
type OneTwoThree = 1 | 2 | 3;
type MyType<num extends OneTwoThree> = {
n: num;
}
const first: MyType = { // <-- Generic type \'MyType\' requires 1 type argument(s).(2314)
n: 2,
};
const second: MyType<3> = {
n: 3,
};
为什么打字稿不能推断first 是MyType<2> 类型?
我也尝试过以这种方式声明MyType:
type MyType<num extends OneTwoThree = OneTwoThree> = {
n: num;
}
但是这样首先变成const first: MyType<OneTwoThree>类型...
有什么建议么?
-
它无法推断,因为它会模棱两可。在
first中,缺少的类型参数可能是2或OneTwoThree,两者都是有效的。唯一合理的选择是提供默认类型或自己指定。
标签: typescript typescript-generics