`MyInterfaceOne[] | 之间有什么区别? MyInterfaceTwo[]` 和`(MyInterfaceOne|MyInterfaceTwo)[]`
Whats the difference between `MyInterfaceOne[] | MyInterfaceTwo[]` and `(MyInterfaceOne|MyInterfaceTwo)[]`
使用 MyInterfaceOne[] | MyInterfaceTwo[]
时,我在代码的不同位置收到 Typescript 错误,这对我来说没有意义。
myInterfaces = funcWithAboveSignature()
return myInterfaces.reduce(async (acc, interfaceType) => {
await acc;
if (interfaceType.prop) {
return await someAsyncFunc(interfaceType);
} else {
return await someOtherAsyncFunc(interfaceType);
}
}, Promise.resolve());
错误说:
Argument of type '(acc: MyInterfaceOne, raw: MyInterfaceOne) => Promise<void>' is not assignable to parameter of type '(previousValue: MyInterfaceOne, currentValue: MyInterfaceOne, currentIndex: number, array: MyInterfaceOne[]) => MyInterfaceOne'.
但是当将函数签名从 MyInterfaceOne[] | MyInterfaceTwo[]
更改为 (MyInterfaceOne|MyInterfaceTwo)[]
时它起作用了。
谁能给我解释一下这两者的区别?
MyInterfaceOne[] | MyInterfaceTwo[]
表示它可以是仅包含 MyInterfaceOne 的数组或仅包含 MyInterfaceTwo 的数组。
(MyInterfaceOne|MyInterfaceTwo)[]
表示它可以是 MyInterfaceOne 或 MyInterfaceTwo 的数组,因此它可以包含这两种类型中的任何一种元素。
使用 MyInterfaceOne[] | MyInterfaceTwo[]
时,我在代码的不同位置收到 Typescript 错误,这对我来说没有意义。
myInterfaces = funcWithAboveSignature()
return myInterfaces.reduce(async (acc, interfaceType) => {
await acc;
if (interfaceType.prop) {
return await someAsyncFunc(interfaceType);
} else {
return await someOtherAsyncFunc(interfaceType);
}
}, Promise.resolve());
错误说:
Argument of type '(acc: MyInterfaceOne, raw: MyInterfaceOne) => Promise<void>' is not assignable to parameter of type '(previousValue: MyInterfaceOne, currentValue: MyInterfaceOne, currentIndex: number, array: MyInterfaceOne[]) => MyInterfaceOne'.
但是当将函数签名从 MyInterfaceOne[] | MyInterfaceTwo[]
更改为 (MyInterfaceOne|MyInterfaceTwo)[]
时它起作用了。
谁能给我解释一下这两者的区别?
MyInterfaceOne[] | MyInterfaceTwo[]
表示它可以是仅包含 MyInterfaceOne 的数组或仅包含 MyInterfaceTwo 的数组。
(MyInterfaceOne|MyInterfaceTwo)[]
表示它可以是 MyInterfaceOne 或 MyInterfaceTwo 的数组,因此它可以包含这两种类型中的任何一种元素。