
[英]Types of property 'length' are incompatible. Type '4' is not assignable to type '1'
[英]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.