Skip to content

Suggestion - Obtaining property type with dot notation on index type #30815

Closed

Description

Search Terms

dot notation, index type

Suggestion

Enable accessing object property type in the type domain, when possible

type Obj = {
    x: number;
    y: number;
}

type X = Obj['x'];
// This would be an error, but it's a much more concise/intuitive syntax
type X2 = Obj.x;

Note this is not the same as #12596, which is a breaking change.
I'm only suggesting allowing Obj.propertyName to be a type,
or as an alias of Obj['propertyName'].
propertyName must have been known to the compiler, as in the old index type.

One possible drawback is it might cause confusion with accessing objects,
but not that much since when reading TS code, people tend to first look
at which part is the typing and which part is the runtime.

Use Cases

This applies to all cases where index type is used without mapped types.
It would improve the readability and reduce a lot of syntax noise.

Examples

Shamelessly copied the code from #17588, and image how this code will look better
with the new syntax :)

CODE

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions