[英]TypeScript Assertion Doesn't work when the property is Record<number,number>
我从一些博客中了解到, typescript 中的T as K
仅在T is subType of K
的子类型或K is subType of T
T 的子类型时才有效,我不知道是真是假。
当我使用as
当属性为Record<T,K>
时, as
抛出一些错误,如下所示。
interface Test {
x: Record<number, number>;
y: number;
}
// this is wrong, but {1: 1} should be subType of Record<number,number>
const x1 = {
x: { 1: 1 },
} as Test;
// this is okay
const x2 = {
y: 1,
} as Test;
// this is okay too
const x3 = {
x: { 1: 1 },
y: 1,
} as Test;
首先,我猜是因为{ 1: 1 }
与 Type Record<number, number>
不匹配,我猜 subType 判断很浅。 但这是另一个可以工作的示例。
interface SubTest {
x: 1;
y: 1;
}
interface Test2 {
x: SubTest;
y: number;
}
// { x: 1 } is subType of SubTest, and It works!
const x4 = {
x: { x: 1 },
} as Test2;
你可以看到{x:1}
也与SubTest
不匹配,但是这个断言可以工作,所以我猜这是Record<T,K>
的一个特殊问题,谁能告诉我为什么? 多谢!
我发现这个可以工作。 所以我现在真的很迷茫...
interface Test {
x: Record<number, number>;
y: number;
}
const x4 = {
x: { a: 1 },
y: 1,
} as Test;
下面的问题不在于Record
。 在接口Test
中,您已将y
定义为必填项,但您没有在此处提供 y。
const x1 = {
x: { 1: 1 },
} as Test;
将y
转换为可选的,如下所示。
改变这个
interface Test {
x: Record<number, number>;
y: number;
}
至
interface Test {
x: Record<number, number>;
y?: number;
}
现在y
是可选的?
. 这应该使您的代码编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.