联合体中不存在Typescript属性

时间:2019-11-21 15:31:08

标签: typescript

我有以下几种类型:

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 3, 5], [2, 4, 6]]])

arr[np.in1d(arr,5).reshape(arr.shape).any(axis=2)] = [0,0,0]
arr

这样定义的功能:

Foo {
 foobar: any
}

Bar {
 fooBarBar: any;
}

用法:

this.api.submit(param: Foo | Bar)

我的假设是打字稿会基于联合来计算,可能是这些模型中的任何一个,那么为什么在这种情况下会抱怨呢?

一种解决方法是使用括号表示法param ['foobar'],错误将消失...

2 个答案:

答案 0 :(得分:2)

您的定义是说param将是 FooBar,但是编译器无法确定您在哪一点致电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和{{1}都是 Foo,则需要intersection types,即:{{ 1}}。

答案 1 :(得分:1)

它按预期工作。

如果它可以是属性为foobar的类型,也可以是类型为不具有的类型,则不能保证该属性存在。

因此,如果您认为每个有效引用中都存在该引用,则可能会遇到麻烦。

因此,TypeScript抱怨。

也许您可以指出Bar可能具有(可能未定义)foobar属性:

Foo {
 foobar: any
}

Bar {
 foobar?: any;
 fooBarBar: any;
}

您应该只使用所有联合类型上都存在的属性。

基本上,您可以将并集类型视为包含所有 common 属性的接口。