I am struggling with defining a TypeScript generic to achieve a specific output.
type Route = {
path: string
children?: readonly Route[]
}
const root = {
path: "a",
children: [
{ path: "b" },
{ path: "c", children: [{ path: "d", children: [{ path: "e" }] }] }
],
} as const satisfies Route;
The goal is to create a TypeScript generic Convert
that will result in the enum 'a' | 'a/b' | 'a/c' | 'a/c/d' | 'a/c/d/e' when used with Convert<typeof root>
.
type Convert<T extends Route> = ?
My attempt so far has not been successful:
type Convert<T extends Route, Prefix extends string = ''> =
`${Prefix}/${T['path']}` | (
T["children"] extends readonly Route[]
? {
[K in number]: Convert<T['children'][K], `${Prefix}/${T['path']}`>;
}[number]
: never)
The current output I get is limited to "/a", "/a/b", and "/a/c", and doesn't go deep enough.
Click here to view and help me on TypeScript Playground
Any assistance would be greatly appreciated!