2

I have a function that nests objects based on the length of an input array. E.g.:

fn(['a']) -> Record<string, string>

fn(['a', 'b']) -> Record<Record<string, string>>

I'm defining the return type as:

type Ret = {
  [k: string]: string | Ret;
}

However, this doesn't know the depth of the object. If the input as a TS tuple, then in theory it should be possible to know the depth of the return type. Is this currently possible?

1
  • AFAIK TypeScript support for dependent types is limited. Your Ret type would need a "depth" parameter that is reduced. So you'd have Ret<0> = string and Ret<n> = {[k: string]: Ret<n-1>}, obviously this syntax is made up. Maybe this article, or this one may help giving you some ideas Commented Jun 16, 2021 at 12:50

1 Answer 1

4

Using a recursively defined conditional type:

type NestedRecord<T extends any[]>
    = T extends [any, ...infer R]
    ? Record<string, NestedRecord<R>>
    : string

Example:

type Test = NestedRecord<['a', 'b']>
// {[x: string]: Record<string, string>}

Playground Link

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.