typescript - 按值从打字稿联合中选择元素
问题描述
我有这种形状的联合:
type Message =
| { type: 'first', someParam: any } // let it be AMsg
| { type: 'second', someAnotherParam: any, andOneAnother: any }
我想将此联合的元素作为单独的类型获取,如下所示:
type AMsg = MessageOfType<'first'> // = { type: 'first', someParam: any }
我尝试编写自己的 MessageOfType:
type MessageOfType<T extends Message['type']> = Message['type'] extends T ? Message : never
但它总是返回never
。
type
我应该使用什么来从联合中获取一个或一些具有匹配所需值的元素?
解决方案
您可以Extract
为此使用预定义的条件类型:
type Message =
| { type: 'first', someParam: any } // let it be AMsg
| { type: 'second', someAnotherParam: any, andOneAnother: any }
type AMsg = Extract<Message, { type: 'first' }>
推荐阅读
- php - 警告在 php 中遇到的非数字值
- ios - Core Data 在一对多关联中双插入子记录
- python - 如何从文件中将值添加到现有的空值键字典?
- segmentation-fault - 即使访问的地址可访问,是否也可能导致段错误?
- c# - 用于将路由模板与请求路径匹配的正则表达式
- python - 如何使用 pexpect 在多个文件上运行 osm2pgsql?坚持“使用 PBF 解析器”。
- cmake - 在另一个目标中包含一个目标的包含目录
- reactjs - React Router 在页脚上渲染页面
- javascript - 将 url 复制到剪贴板后显示成功消息
- python - 在 Spyder 中安装 Python 3.6