Daniel
Daniel

Reputation: 1472

Why does the type change in this simple map?

Why does this uneventful map change the type of the array?

I am doing a more complicated map than this but the goal is to keep the type the same through the map.

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

I am using typescript 4.3.5.

Upvotes: 3

Views: 305

Answers (1)

Rubydesic
Rubydesic

Reputation: 3476

This is the signature of Array<T>#map:

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

T here is inferred to be type1 | type2, and U is inferred to be the same as T. Then the method returns U[] which is (type1 | type2)[].

Upvotes: 2

Related Questions