DEV Community

Discussion on: I need to learn about TypeScript Template Literal Types

Collapse
 
nroboto profile image
Mike Nightingale

The issue is that in the Subpath type we exclude all of the properties of an array, which includes the length property, this results in foo.length being excluded even though in this case length is a property on an object. One way to fix this is to change the exclusion to only apply if the type is an array:

type ExcludeArrayKeys<T> = Exclude<keyof T, T extends any[] | readonly any[] ? keyof any[] : never>

type Subpath<T, Key extends keyof T = keyof T> = (
  T[Key] extends Record<string, any> ?
    `${Key & string}.${Path<T[Key], ExcludeArrayKeys<T[Key]>>}`
  :
    never);
Enter fullscreen mode Exit fullscreen mode

Here's the TS playground.