Skip to content

Support dotted path notation #154

@nandorojo

Description

@nandorojo

🍩 Feature Request

Is your feature request related to a problem?

TypeScript 4.1 has template literals, and they're super useful. However, the only solutions out there are quite hacky to use, and result in some bugs.

I want to be able to get a nested object path, as shown in this repo.

Describe the solution you'd like

import { Object } from 'ts-toolbelt'

type I = { hi: { hey: true } }

type Nested = Object.NestedPath<I, 'hi.hey'>

I want to know how do I get the nested object path using dot notation of an object. I'd then like to get the value that matches that object with the path.

I'd like to achieve this:

Screen Shot 2020-10-31 at 11 15 12 AM

This is the idea:

type Path<T, Key extends keyof T = keyof T> =
Key extends string
? T[Key] extends Record<string, any>
  ? | `${Key}.${Path<T[Key], Exclude<keyof T[Key], keyof Array<any>>> & string}`
    | `${Key}.${Exclude<keyof T[Key], keyof Array<any>> & string}`
    | Key
  : never
: never;

type PathValue<T, P extends Path<T>> =
  P extends `${infer Key}.${infer Rest}`
  ? Key extends keyof T
    ? Rest extends Path<T[Key]>
      ? PathValue<T[Key], Rest>
      : never
    : never
  : P extends keyof T
    ? T[P]
    : never;


declare function get<T, P extends Path<T>>(obj: T, path: P): PathValue<T, P>;

However, this code block above seems to be buggy. I occasionally get infinite loop errors from typescript if I use it (but not always), so someone who has a better understanding of TS than I do should probably make it.

Describe alternatives you've considered

I tried the code sample above. However, it is not very robust. Someone put it on twitter, but I think it would make more sense for it to live in TS toolbelt (which is always so helpful.)

Teachability, Documentation, Adoption, Migration Strategy

This is a great article describing the template literals. Surprisingly, if you google "TypeScript template literals," it's hard to find content, even though it's such a cool addition. Do you think you might be able to help @millsp? Thank you so much!

Metadata

Metadata

Assignees

Labels

featureAdd new features

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions