我有以下几种类型:
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'],错误将消失...
答案 0 :(得分:2)
您的定义是说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
和{{1}都是 和Foo
,则需要intersection types,即:{{ 1}}。
答案 1 :(得分:1)
它按预期工作。
如果它可以是属性为foobar
的类型,也可以是类型为不具有的类型,则不能保证该属性存在。
因此,如果您认为每个有效引用中都存在该引用,则可能会遇到麻烦。
因此,TypeScript抱怨。
也许您可以指出Bar
可能具有(可能未定义)foobar
属性:
Foo {
foobar: any
}
Bar {
foobar?: any;
fooBarBar: any;
}
您应该只使用所有联合类型上都存在的属性。
基本上,您可以将并集类型视为包含所有 common 属性的接口。