3

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]
2
  • 3
    Would this work? tsplay.dev/W4XPeW If so, I can post an answer. Commented Dec 4, 2022 at 15:30
  • 1
    @Oblosys: post this as an answer Commented Dec 4, 2022 at 16:30

1 Answer 1

2

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

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

2 Comments

hey, that looks promising! would you mind sharing a very simple example of what the implementation would look like? I'm having a trouble returning an array that would fit the returned type
@TomaszMularczyk You won't be able to this in a typed way, so you'll need to assert it with as unknown as StringTuple<N> (or just as unknown if the signature of func already specifies return type StringTuple<N>).

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.