联合中不存在Typescript属性
我有以下几种:联合中不存在Typescript属性,typescript,Typescript,我有以下几种: Foo { foobar: any } Bar { fooBarBar: any; } 这样定义的函数: this.api.submit(param: Foo | Bar) 用法: this.api.submit(param.foobar) // does not exist on Bar Error: Property 'foobar' does not exist on type 'Foo| Bar'. Property 'foobar' does not e
Foo {
foobar: any
}
Bar {
fooBarBar: any;
}
这样定义的函数:
this.api.submit(param: Foo | Bar)
用法:
this.api.submit(param.foobar) // does not exist on Bar
Error: Property 'foobar' does not exist on type 'Foo| Bar'.
Property 'foobar' does not exist on type 'Bar '
我的假设是,typescript将根据联合来计算,它可能是这两种模型中的任何一种,那么它为什么在这种情况下抱怨呢
解决方法是使用括号符号param['foobar'],错误将消失 您的定义是
param
将是或者Foo
或者Bar
,但是编译器无法决定在调用param.foobar
时调用哪个
如果您希望能够辨别,您可以这样做:
Foo {
type: 'foo',
foobar: any
}
Bar {
type: 'bar',
fooBarBar: any;
}
...
if (param.type === 'foo') {
param.foobar; // the type guard in the if statement guarantees we've got an instance of Foo here
}
如果你想说的是
param
将同时Foo
和Bar
,你需要,也就是说:Foo&Bar
,它正在按预期工作
如果它可以是具有属性foobar
的类型,也可以是不具有属性的类型,则不能保证该属性存在
因此,如果假设它存在于每个有效引用中,您可能会遇到麻烦
因此,TypeScript抱怨道
也许您可以指出Bar
可能具有(可能未定义的)foobar
属性:
Foo{
有吗
}
酒吧{
foobar?:任何;
巴巴拉:任何;
}
您应该只使用所有联合类型上已知的属性
基本上,您可以将联合类型视为包含所有公共属性的接口。您可以将变量强制转换为特定类型:
(参数为Foo)。foobar
,但是,如果没有属性foobar,为什么要允许类型Bar,你想在任何情况下使用属性foobar吗?括号表示法基本上是“与typescript对抗”,通过绕过任何检查。它破坏了在JS上使用类型化语言的“保护”的全部意义。是的,我知道——只是说人们总是可以回到JS类型的黑客:Pnice使用防护,但是你不能使用“内置”类型防护吗?类似于param的东西是Bar
在交叉点类型上刚刚拾取的,谢谢+1@Pac0但是,不能直接执行if((参数为Foo.foobar){…}
,但它看起来有点难看。您还可以定义typeguard函数,例如函数isFoo(p):p是Foo{return(p是Foo).foobar;}
,然后说if(isFoo(param)){…}