简体   繁体   English

TypeScript 断言在属性为记录时不起作用<number,number></number,number>

[英]TypeScript Assertion Doesn't work when the property is Record<number,number>

I learn from some blog that T as K in typescript only work when T is subType of K or K is subType of T ,I don't know whether it's true of not.我从一些博客中了解到, typescript 中的T as K仅在T is subType of K的子类型或K is subType of T T 的子类型时才有效,我不知道是真是假。

And when I using as when the property is Record<T,K> , as throw some error as below.当我使用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;

First, I guess It's because { 1: 1 } doesn't match the Type Record<number, number> , I guess the subType judge is shallow.首先,我猜是因为{ 1: 1 }与 Type Record<number, number>不匹配,我猜 subType 判断很浅。 But here is another sample that can work.但这是另一个可以工作的示例。

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;

You can see {x:1} doesn't match SubTest too, but this assertion can work, so I guess it's a special problem of Record<T,K> ,can anyone tell me why?你可以看到{x:1}也与SubTest不匹配,但是这个断言可以工作,所以我猜这是Record<T,K>的一个特殊问题,谁能告诉我为什么? thanks a lot!多谢!


I found out this one can work.我发现这个可以工作。 so I'm really cofunsed right now...所以我现在真的很迷茫...

interface Test {
    x: Record<number, number>;
    y: number;
}

const x4 = {
    x: { a: 1 },
    y: 1,
} as Test;

The problem with below is not with the Record .下面的问题不在于Record In interface Test you have defined y as mandatory but you have not provided y here.在接口Test中,您已将y定义为必填项,但您没有在此处提供 y。

const x1 = {
    x: { 1: 1 },
} as Test;

Convert y to optional like below.y转换为可选的,如下所示。

Change this改变这个

interface Test {
    x: Record<number, number>;
    y: number;
}

To

interface Test {
    x: Record<number, number>;
    y?: number;
}

Now y is made optional with ?现在y是可选的? . . This should make your code compile.这应该使您的代码编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM