How can I ensure an array is passed a certain number of parameter in a function apart from using a tuple

How can I ensure an array is passed a certain number of parameter in a function apart from using a tuple

I have a function in typescript which takes an array as a parameter and when the function is called i want a certain number of elements to be passed in the array how can I achieve this apart from using a tuple

type a =(arr: [number, number]) => boolean
const b:a = (arr) => {}
b([]) // should throw an error if the parameter passed in array is less than two

How can I achieve this without using tuples

>Solution :

You could extend Array<number> with a specific length and types for each index:

interface TupleOfTwoNumbers extends Array<number> {
    length: 2;
    0: number;
    1: number;
}

type a = (arr: TupleOfTwoNumbers) => boolean

const b: a = (arr) => true

b([]);        // !
b([1]);       // !
b([1, 2]);    // ok
b([1, 2, 3]); // !

but the errors generated aren’t as helpful:

Argument of type ‘[]’ is not assignable to parameter of type ‘TupleOfTwoNumbers’.(2345)

compared to using tuples:

Argument of type ‘[]’ is not assignable to parameter of type ‘[number, number]’.
Source has 0 element(s) but target requires 2.(2345)

Playground

Leave a Reply