首页 > 解决方案 > 按值从打字稿联合中选择元素

问题描述

我有这种形状的联合:

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我应该使用什么来从联合中获取一个或一些具有匹配所需值的元素?

标签: typescript

解决方案


您可以Extract为此使用预定义的条件类型:

type Message = 
  | { type: 'first', someParam: any } // let it be AMsg
  | { type: 'second', someAnotherParam: any, andOneAnother: any }

type AMsg = Extract<Message, { type: 'first' }>

游乐场链接


推荐阅读