網站搜尋

typescript - 為什麼在這個簡單的 map 中類型會改變?


為什麼這個平淡無奇的地圖會改變陣列的類型?

我正在做一個比這個更複雜的地圖,但目標是在整個地圖中保持類型相同。

  const x: type1[] | type2[]=[]; // x has type type1[] | type2[]
  const y = x.map(item=>item);   // y has type (type1 | type2)[]

我正在使用 TypeScript 4.3.5。

答案#1

這是 Array<T>#map 的簽名:

map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

T 在這裡被推斷為 type1 | type2,而 U 被推斷為與 T 相同。然後該方法返回 U[],即 (type1 | type2)[]。