Skip to content

Self referencing type with maximum depthΒ #226

@nandorojo

Description

@nandorojo

🍩 Feature Request

Is your feature request related to a problem?

I'm creating a navigation sidebar. It has dropdowns, with nested dropdowns inside of those (optionally).

Imagine this type of thing:

  • Settings
    • Account
      • Notifications
      • Security
        • Password

Is there a way I can self-reference a MenuItem that has dropdownItems?: MenuItem with a maximum depth?

Describe the solution you'd like

Pseudocode (of how I imagine code should work):

type MenuItem<Depth extends number> = {
  name: string
  dropdownItems?: Depth > 0 ? MenuItem<Depth - 1>[] : never
}

Describe alternatives you've considered

import { Number } from 'ts-toolbelt'

type MenuItem<Depth extends number> = {
    name: string
    dropdownItems: Number.Greater<Depth, 0> extends true ? MenuItem<Number.Sub<Depth, 1>>[] : never
}

const menuItem: MenuItem<1> = {
    name: 'Products',
    dropdownItems: [{
        name: 'Edit',
    }]
}

However, this does not work. It looks like dropdownItems sets to never, and my menuItem variable fails.

Here's a playground link: https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=13&pc=2#code/JYWwDg9gTgLgBAbzgOQK4gEYFMpwL5wBmUEIcA5DAM4C0MEEANtozOQFDswCeYWcAWSwA7VAEkYWEAB4AIljAwAFnCwAPScIAmVOKMw4AfHAC8idnEt6AhiCwAuOFRhRgwgOYWrWkmC0QAd2EJKSpHNAMoADoAcSgsa0koOQVlABo4AAZjdU0dOBdUfgB+QRFxSRkI7GiAZVQMFMUlDIBGQ0MAbQBdOEdhLAA3HHY8TgBjCGFnODtREJBHIXnK6XbTcysbO0dyAAUSLVRx6nI0r0sfCD9A4MqwuE6EC63thwoAUS1gNnOtvG6oyAA

Teachability, Documentation, Adoption, Migration Strategy

One thing that trips me up a bit: the docs use strings as the generics for Number.GreaterThan, but this doesn't seem to be in the types. Not sure if that's relevant: https://millsp.github.io/ts-toolbelt/modules/number_greatereq.html

Thanks again for your help!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions