[英]Property does not exist when using union type in typescript
Suppose that I have two interfaces:假设我有两个接口:
interface Box {
x: number
y: number
}
and和
interface ColouredBox {
x: number
y: number
colour: string
}
Assume for the purpose of this question, that I cannot change the interfaces.就这个问题而言,假设我无法更改接口。
Now when constructing objects, I have code like this:现在在构造对象时,我有这样的代码:
let a: Box|ColouredBox = {x: 1, y: 2}
if( something ){
a.colour = "Blue" // Compilation Error
}
I get this error on a.colour = "Blue"
:我在a.colour = "Blue"
上收到此错误:
Error:(24, 26) TS2339: Property 'colour' does not exist on type 'Box'.
Why?为什么? Is this a limitation of the TS compiler?这是 TS 编译器的限制吗? Other than completely reconstructing the object, is there a different workflow that I could use?除了完全重建对象之外,我可以使用其他工作流程吗?
You can use the in
type guard :您可以使用in
类型保护:
if ("colour" in a) {
a.colour = "Blue" // works
}
This will narrow to the union part ColouredBox
based on the existence of property colour
.这将根据属性colour
的存在缩小到联合部分ColouredBox
。 In general, you can only select all common properties x
/ y
of Box | ColouredBox
一般情况下,只能选择Box | ColouredBox
所有常用属性x
/ y
。 Box | ColouredBox
, when not narrowed before. Box | ColouredBox
,当之前没有缩小时。
Using a Partial使用部分
Instead of using a union type, you can try using a Partial您可以尝试使用Partial ,而不是使用联合类型
let a: Partial<ColouredBox> = {x: 1, y: 2}
The partial will set all the properties of the ColoredBox
as optional.部分会将ColoredBox
所有属性设置为可选。
Update :更新:
Eliminate an Interface消除接口
If you only want the color part of the interface to be optional, you can eliminate one of the interfaces.如果你只希望界面的颜色部分是可选的,你可以去掉其中一个界面。
interface Box {
x: number;
y: number;
color?: string;
}
Then to determine if you're dealing with a colored box:然后确定您是否正在处理彩色框:
if (box.color) { ... }
Type Assertion类型断言
If you stick to using both interfaces, you can specifically treat a
as a ColouredBox
using the as
keyword (aka a Type Assertion).如果您坚持使用这两个接口,则可以使用as
关键字(也称为类型断言)专门将a
视为ColouredBox
。
let a: Box | ColouredBox = { x: 1, y: 2 };
(a as ColouredBox).colour = "Blue";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.