網站搜尋

typescript - `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)[] 時,它就能正常工作。

有人可以給我解釋這兩者之間的差別嗎?

答案#1

MyInterfaceOne[] | MyInterfaceTwo[]

表示它可以是僅包含 MyInterfaceOne 的陣列,或僅包含 MyInterfaceTwo 的陣列。

(MyInterfaceOne|MyInterfaceTwo)[]

表示它可以是 MyInterfaceOne 或 MyInterfaceTwo 的陣列,因此它可以包含任一類型的元素。