1

i try to get correct typescript types as dot notation but without the deepest child.

i found half of my solution here: Typescript string dot notation of nested object. But this doesn't include omitting the deepest child.

Here an example:

type TranslationType = {
  key1: {
    en: string,
  }
  sub: {
    key2: {
      en: string,
    }
  }
}

type PathsToStringProps<T> = T extends string
  ? []
  : {
      [K in Extract<keyof T, string>]: [K, ...PathsToStringProps<T[K]>]
    }[Extract<keyof T, string>]

type Join<T extends string[]> = T extends []
  ? never
  : T extends [infer F]
  ? F
  : T extends [infer F, ...infer R]
  ? F extends string
    ? `${F}.${Join<Extract<R, string[]>>}`
    : never
  : string

let value: Join<PathsToStringProps<TranslationType> // "key1.${string}" | "sub.key2.${string}"

I get "key1.${string}" | "sub.key2.${string}" but i want it to be "key1" | "sub.key2".

TheWuif
  • 988
  • 6
  • 11

1 Answers1

0

Not my best Typescript I ever wrote, but its working

type Join<T extends string[]> = T extends [string]
  ? never
  : T extends [infer F, ...infer R]
  ? F extends string
    ? Join<Extract<R, string[]>> extends never
      ? `${F}`
      : `${F}.${Join<Extract<R, string[]>>}`
    : never
  : string;
Zokki
  • 125
  • 1
  • 8