Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading