Search code examples
typescripttuplestype-inference

Is there a way to make it a type inference of an array imported as a splice function from different types of tuples?


For example, let's say there's a code below.

type MyType = 'a' | 'b' | 'c';

const a = [3, 5, 'a', 'b'] as const;

const func = (arg: readonly [number, number, ...MyType[]]) => {
    const myTypeArr = arg.slice(2); // i want this type "MyType[]" !!!
};

func(a);

I hope that the "myTypeArr" variable is inferred as MyType[].

However, it is actually inferred as (number | MyType)[].

I did a search to implement it, but I couldn't.


Solution

  • Can use destructuring to achieve this:

    type MyType = 'a' | 'b' | 'c';
    
    const a = [3, 5, 'a', 'b'] as const;
    
    const func = (arg: readonly [number, number, ...MyType[]]) => {
        // myTypeArr will have type MyType[]
        const [ , , ...myTypeArr] = arg;
    };
    
    func(a);