3

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?

4
  • 2
    If you are using a recent version of TS, the other answer there is better namely type ArrayTwoOrMore<T> = [T, T, ...T[]], but you still need to spell out all members, no way to say greater than N Commented Jun 23, 2020 at 13:40
  • For info: typescript-how-to-declare-array-of-fixed-size-for-type-checking-at-compile-time Commented Jun 23, 2020 at 15:01
  • In Typescript you can create types like this type Pair<T, U> = [T, U] and type Tripple<T> = [T, T, T] I think @TitianCernicova-Dragomir answer is the best you can get with typescript in one line of code Commented Jun 24, 2020 at 9:53
  • not sure why I did not think of this yesterday, in 4.0 this will be easier. 10x @IAMTHEBEST for bringing the question back in my mind :) Commented Jun 24, 2020 at 10:34

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.