[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'
}

 

posted @ 2022-09-28 14:03  Zhentiw  阅读(4)  评论(0编辑  收藏  举报