Skip to content

Add a built-in helper type for dotted object path literals and path tuples Β #46337

Closed
@thw0rted

Description

@thw0rted

Suggestion

πŸ” Search Terms

object key dotted path template literal helper type

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

I'd like to see a built-in helper type that takes an interface as a generic param, and returns either the union of all dotted-notation key paths, or tuples of valid paths:

interface Foo {
  a: {
    b: {
      c: number;
    }[];
    d: boolean;
  }
}

type FooPath = ObjectKeyPath<Foo>; // "a" | "a.b" | `a.${number}.c` | "a.d";
type FooTuple = ObjectKeyTuple<Foo>; // ["a"] | ["a", "b"] | ["a", number, "c"] | ["a", "d"];

πŸ“ƒ Motivating Example

Both of these notations are commonly used in libraries around the ecosystem. Many end users try to create similar complex types themselves, with results of varying quality, that may miss important edge cases or perform much worse than an optimal implementation would. I understand that there may have to be similar limitations on a built-in type, for recursive or excessively-deep inputs, but these could at least be thoughtfully designed and documented, with useful error messages.

πŸ’» Use Cases

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions