[Typescript] Tips: Use 'in' operator to transform a union to another union(watched)
We want to convert
export type Entity =
| {type: "user"}
| {type: "post"}
| {type: "comment"}
to
type EntityWithId =
| {type: "user", userId: string}
| {type: "post", postId: string}
| {type: "comment", commentId: string}
export type Entity =
| {type: "user"}
| {type: "post"}
| {type: "comment"}
export type EntityWithId = {
[Key in Entity["type"]]: {
type: Key
} & Record<`${Key}Id`, string>
}[Entity["type"]]
const result: EntityWithId = {
type: 'comment',
commentId: '123'
}