Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type array length dynamically with Typescript

Is it possible to do type array length based on a number variable? example:

func(1); // returns [string]
func(2); // returns [string, string]
func(5); // returns [string, string, string, string, string]
like image 314
Tomasz Mularczyk Avatar asked Feb 07 '26 06:02

Tomasz Mularczyk


1 Answers

You can declare a recursive conditional type StringTuple to create string tuples of a specific length N:

type StringTuple<N extends number, T extends string[] = []> =
  N extends T['length'] ? T : StringTuple<N, [...T, string]>

StringTuple constructs the desired string tuple in an accumulating parameter T, to which an extra string is added until its length is equal to N.

type Test = StringTuple<3>
// type Test = [string, string, string]

Given StringToTuple, the signature of func is straightforward:

declare const func: <N extends number>(length: N) => StringTuple<N>

const t1 = func(1)
// const t1: [string]

const t2 = func(2)
// const t2: [string, string]

const t5 = func(5)
// const t5: [string, string, string, string, string]

TypeScript playground

like image 193
Oblosys Avatar answered Feb 09 '26 02:02

Oblosys