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]
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]
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]
as unknown as StringTuple<N> (or just as unknown if the signature of func already specifies return type StringTuple<N>).