首页 > 其他分享 >[Typescript] Tips: Use 'in' operator to transform a union to another union(watched)

[Typescript] Tips: Use 'in' operator to transform a union to another union(watched)

时间:2022-09-28 14:12:37浏览次数:55  
标签:comment Use Typescript string union Entity export type

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

 

标签:comment,Use,Typescript,string,union,Entity,export,type
From: https://www.cnblogs.com/Answer1215/p/16737837.html

相关文章

  • P2. TypeScript 基本语法
    TypeScript是区分大小写的TSC常用编译参数--help#显示帮助信息 --module#载入扩展模块 --target#设置ECMA版本--declaration#额外生成一个.d.ts扩展名的......
  • JuiceFS 在 Elasticsearch/ClickHouse 温冷数据存储中的实践
    企业数据越存越多,存储容量与查询性能、以及存储成本之间的矛盾对于技术团队来说是个普遍难题。这个难题在Elasticsearch与ClickHouse这两个场景中尤为突出,为了应对不同......
  • docker集成分词器时报Caused by: java.nio.file.FileSystemException: /usr/share/ela
    官网https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v6.8.6下载好的zip包cp到/usr/share/elasticsearch/plugins/下后解压它会带有一个config包,或者......
  • 引用 | pip install keybert | ERROR: Could not build wheels for tokenizers which
    window10安装keybert出错以下错误:runningbuild_extrunningbuild_rusterror:can'tfindRustcompilerIfyouareusinganoutdatedpipversion,it......
  • 据库连接中useSSL
    在进行数据库连接时:jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf8jdbc.username=......
  • [Typescript] 39. Medium - AnyOf
    ImplementPythonliked any functioninthetypesystem.AtypetakestheArrayandreturns true ifanyelementoftheArrayistrue.IftheArrayisempty,......
  • 如何从3dwarehouse获取模型(非商用)
        这是需要一些模型做练习时,从网上下载的开放模型,非商业应用,否则会被网站追责版权!    3dwarehouse的模型一般都放在谷歌地球上去展示,打开谷歌地球就可以看......
  • 四、typescript类属性的封装
    类属性的封装:通过属性的修饰符实现private:只有在类的内部进行访问和修改public:可以在任意位置访问和修改。默认时publicprotected:可以在当前类和当前类的子类中访问......
  • TypeScript工具类 Partial 和 Required 的详细讲解
    场景描述:场景描述:一个接口(IPerson)有很多个的字段,可能有几百。而且这些字段都是必须的。我们需要使用这个接口,但是我又不可能使用它的全部。可能只会使用几个。我还必......
  • Full House
    ProblemStatementWehavefivecardswithintegers$A$,$B$,$C$,$D$,and$E$writtenonthem,oneoneachcard.ThissetoffivecardsiscalledaFullhouse......