Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript array with arbitrary minimum length N, which can be large

I want to create a type where an array has a minimum length of N. I have looked at this TypeScript array with minimum length , but when N is large, I do not want to write out the type from 0 to N, e.g. :

type ArrayTwoOrMore<T> = {
    0: T
    1: T
    ...
    N: T
}

I was wondering whether there was a neater way of doing this?

like image 619
wtwtwt Avatar asked Apr 01 '26 04:04

wtwtwt


1 Answers

You can't do arbitrary tuple size, but in 4.0 you will be able to create a type like Typle5 or Tuple10 and spread that multiple times to get to the desired type faster:

type Tuple5<T> = [T, T, T, T, T]
type Tuple10<T> = [...Tuple5<T>, ...Tuple5<T>]
type Tuple50<T> = [...Tuple10<T>, ...Tuple10<T>, ...Tuple10<T>, ...Tuple10<T>, ...Tuple10<T>]
type Tuple100<T> = [...Tuple50<T>, ...Tuple50<T>]

let a: Tuple100<number> = [] // Source has 0 element(s) but target requires 100

Playground Link

I would question the sanity of creating a tuple of size 100 though.

NOTE: 4.0 is still in beta should be released in August 2020

like image 197
Titian Cernicova-Dragomir Avatar answered Apr 03 '26 18:04

Titian Cernicova-Dragomir



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!