Home > Enterprise >  How to keep type information when destructuring an array of two types in typescript?
How to keep type information when destructuring an array of two types in typescript?

Time:10-08

How can I concatenate two arrays of different type A and B and keep it with separate typings as a result and not just

Array<A | B>

and destructuring array back I want to keep types

const [a1, a2] = concatenated;
const [,, b1, b2] = concatenated;

CodePudding user response:

You can't do this with arbitrary length arrays. If they have fixed lengths, then you can handle it:

const a = [1,2] as [number, number];
const b = ['hello', 'bye'] as [string, string];

const c = [...a, ...b] as [number, number, string, string];
const [w, x, y, z] = c; // w and x are numbers, y and z are strings.

CodePudding user response:

You can use extra function for this purpose:

type Value = string | number

const concat = <
    A extends Value,
    ATuple extends A[],
    B extends Value,
    BTuple extends B[]
>(a: [...ATuple], b: [...BTuple]): [...ATuple, ...BTuple] => [...a, ...b]


// [1, 2, "hello", "bye"]
const result = concat([1, 2], ['hello', 'bye'])

const [a /** 1 */, b, c /** "hello" */, d] = result

Playground

Thanks to function argument inference, every element of the tuple is properly infered

More information avout inference on function arguments you can find in my blog

  • Related