Typescript: Generate discriminating map for union types by selecting property as a key.

Created on 24 Jan 2019  路  2Comments  路  Source: microsoft/TypeScript

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:

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

All 2 comments

Already possible:

type X = ["a", number] | ["b", string] | ["c"];
type Y = {
  [K in X[0]]: Extract<X, {0: K}>
}

Oh interesting. You can do it the other way! It appears you can do this with objects as well.

type X = {0:"a", 1:number} | ["b", string] | ["c"];
type Y = {
  [K in X[0]]: Extract<X, {0: K}>
}

This is a really neat trick. Thanks for sharing. I wish this was more discoverable!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wmaurer picture wmaurer  路  3Comments

kyasbal-1994 picture kyasbal-1994  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

weswigham picture weswigham  路  3Comments

bgrieder picture bgrieder  路  3Comments