Skip to content

Generate discriminating map for union types by selecting property as a key. #29551

@ccorcos

Description

@ccorcos

Suggestion

Given a union type:

type X = ["a", number] | ["b", string] | ["c"]

It would be nice to have a mapping from the first element in the tuple to the tuple type. I think a common sense way to do this would be to generate a map using the key in syntax:

type Y = {
  [T[0] in X]: T
}

However, that doesn't work. I think this could be very powerful for unions of objects as well rather than having to hardcode the relationship yourself.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions