繁体   English   中英

输入'{状态:字符串; }' 不可分配给类型 'MyType'。 属性“状态”的类型不兼容。 类型“字符串”不可分配给类型

[英]Type '{ status: string; }' is not assignable to type 'MyType'. Types of property 'status' are incompatible. Type 'string' is not assignable to type

我有一个 .ts 文件,我想使用以下类型定义:

type MyType = {
    status: "ACTIVE" | "INACTIVE"
}

当我将这种类型用于直接设置值的变量时,一切都很好:

const myObj1: MyType = {
    status: "ACTIVE"
}

但是,如果我使用变量来设置值,则会出现错误:

const data = {
    status: "ACTIVE"
}
const myObj2: MyType = data

错误:

Type '{ status: string; }' is not assignable to type 'MyType'.
  Types of property 'status' are incompatible.
    Type 'string' is not assignable to type '"ACTIVE" | "INACTIVE"'.

你可以在这里试穿

我尝试了不同的选项(像这样),但问题是我的类型是从 Json 模式生成的,我无法编辑生成的文件。

这是因为data中的status被推断为string ,而MyType期望它是"ACTIVE""INACTIVE" 你只需要使用as const断言

type MyType = {
    status: "ACTIVE" | "INACTIVE"
}


const myObj1: MyType = {
    status: "ACTIVE"
}


const data = {
    status: "ACTIVE"
} as const
const myObj2: MyType = data

或者您可以使用 TS 4.9 中提供的新的satisfies关键字

type MyType = {
    status: "ACTIVE" | "INACTIVE"
}

const myObj1: MyType = {
    status: "ACTIVE"
}

const data = {
    status: "ACTIVE"
} satisfies MyType

操场

暂无
暂无

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

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