I’m sure this is the expected behaviour but it looks counter-intuitive for me. Given the following snippet, why is item
inferred as { a: number }
instead of { b: number }
? I was expecting a kind of overriding in Options & { activities: Array<{ b: number }>}
.
I’ve discovered that replacing options
param type by Omit<Options, 'activities'> & { activities: Array<{ b: number }> }
solves the problem, but I would like to understand why TS works this way to get the need of an Omit<>
.
Here’s the code so you can copy-paste:
type Activity = { a: number };
type Options = { activities: Activity[] }
const fun = (options: Options & { activities: Array<{ b: number }> }) => {
return options.activities.map(item => item.b)
}
I was expecting an overriding of activities
property so it gets { b: number }[]
type.
2
Answers
The
&
operator is not recursive and doesn’t override anything.The goal of typescript is to make code better not worse.
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types
IMHO a missing feature in TS type system:
Type intersection is not recursive. Given
Types
ActivityA[] & ActivityB[]
and(ActivityA & ActivityB)[]
clearly dont behave the same way.