联合中不存在 Typescript 属性 [英] Typescript property does not exist in a union
问题描述
我有以下类型:
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 会根据联合计算它可能是这些模型中的任何一个,那么为什么它会在这种情况下抱怨?
My assumption was typescript would figure based on the union it could be either of these models, so why does it complain in this instance?
一种解决方法是使用括号表示法 param['foobar'] 并且错误将消失...
A workaround is to use the bracket notation param['foobar'] and the error will disappear...
推荐答案
你的定义是说 param
将是 either Foo
或Bar
,但编译器无法决定在您调用 param.foobar
时调用哪个.
What your definition says is that param
will be either Foo
or Bar
, but there's no way for the compiler to decide which at the point you call param.foobar
.
如果你想能够区分,你可以这样做:
If you want to be able to discriminate, you can do something like this:
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
将是 both Foo
和 Bar
,你需要 交叉点类型,即:Foo &条形
.
If what you wanted to say is that param
will be both Foo
and Bar
, you need intersection types, i.e.: Foo & Bar
.
这篇关于联合中不存在 Typescript 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!