Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that array of tuples (2d array) has at least 1 item in Typescript

I have a simple type check in my Typescript variable declaration that ensures all elements in an array of tuples are of length 2 and are both numbers:

const testArea: [number, number][] = [[0, 0], [0, 220000], [220000, 220000], [220000, 0]];

This allows me to correctly initialise the variable, however it still allows an empty array:

const testArea: [number, number][] = []; // No error

I have tried to re-write this as:

const testArea: [[number, number]] = [[0, 0], [0, 220000], [220000, 220000], [220000, 0]]; // error: only allows a single tuple in the array

but that didn't work for the primary case of many tuples in the array (though it does seem to prevent an empty array from being valid).

How can I check that the outer array contains tuples of type [number, number] and also that it contains at least 1 of these tuples?

like image 366
Harry Avatar asked Dec 03 '25 17:12

Harry


1 Answers

You just need to use small trick with rest operator

type Tuple = [number, number]

type NonEmptyArray<T> = [T, ...T[]];

type Data = NonEmptyArray<Tuple>

const data: Data = [] // error
const data1: Data = [[]] // error
const data2: Data = [[1]] // error
const data2: Data = [[1,1]] // Ok

There are many alternatives to make sure the array is not empty,

here is the other one:

type NonEmptyArray2<T extends unknown[]> = T['length'] extends 0 ? never : T

You can take a look on @jcalz's answer here

like image 50
captain-yossarian Avatar answered Dec 06 '25 11:12

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!