e); entr" /> e); entr" /> e); entr"/>

TypeScript preserving Union Type after destructuring

41 Views Asked by At

Consider the following TypeScript snippet:

const entries = [["a", 1], ["b", 2]] as (["a", 1] | ["b", 2])[];
const mapped = entries.map((e) => e);

entries is typed as an array of a union of tuples.
mapped retains the type of entries as (["a", 1] | ["b", 2])[]. However, when destructuring e in Array.map like so: (Playground link)

// ...
const mapped = entries.map(([k, v]) => [k, v] as const);

mapped is now of type ["a" | "b", 1 | 2][], due to the way TypeScript handles unions.

How can I keep the intended output type like the input type?
How do I need to modify the type signature of Array.map (preferably) or the definition of the callback function itself to achieve this? I need to be able to apply strongly typed transformations to the output, say

// ... import Uppercase<> ...
entries.map(([k, v]) => [k.toUpperCase(), v] as [Uppercase<typeof k>, typeof v]);`.
// expected: (["A", 1] | ["B", 2])[]
0

There are 0 best solutions below