Running into an issue with my TypeScript code snippet where the mapped type is losing intersection type information inside the map()
.
type Foo = { foo: number };
type Bar = { bar: string };
const arr: Foo[] & Bar[] = [{ foo: 1, bar: 'bar' }];
// const arr: (Foo & Bar)[] = [{ foo: 1, bar: 'bar' }]; // This version works
const item = arr[0]; // item: Foo & Bar
item.bar.length; // 3
arr.map((item) => item.bar.length); // item: Foo. Why?
The issue lies in the conversion of types within the map() function. While access to arr[0] correctly shows the type as Foo & Bar, within the map() function it only reflects as Foo, causing a type error when attempting to access item.bar.length.
Why does TypeScript lose the intersection type details in the map() function? How can I ensure that both Foo and Bar properties are preserved in the type? Although the commented-out version resolves the issue, understanding why the original code fails would be helpful.
Your assistance on this matter is much appreciated.
I have provided a working alternative using the correct type notation (Foo & Bar)[]
, but the confusion remains over the loss of intersection type information in the initial code.