wtwtwt
wtwtwt

Reputation: 388

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?

Upvotes: 3

Views: 1050

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

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

Upvotes: 3

Related Questions