如何将键名映射到打字稿对象的值类型

时间:2020-12-22 01:20:51

标签: typescript

我有以下内容:

type MSH = {
  val1: string
}

type EVN = {
  val2: string
}

type PID = {
  val3: string
}
type Segment = MSH | EVN | PID

type Segments = {
  MSH: MSH
  EVN: EVN
  PID: PID
}

是否有避免在 Segments 中重复键类型映射的方法?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作

type Segments = {
  MSH: {val1:string}
  EVN: {val2:string}
  PID: {val3: string}
}

type Segment = Segments[keyof Segments]

然后当你想单独使用 MSH、ENV 或 PID 的类型时,你可以使用

Segments['MSH']
Segments['EVN']
Segments['PID']

而不是明确地重新定义类型 MSHEVNPID

答案 1 :(得分:0)

对我来说最好的解决方案是定义一个按键/类型对类型进行分组的接口 然后通用来选择每个键。它看起来像 Typescript Pick。

interface Segments {
  MSH: MSH,
  ENV: EVN,
  PID: PID,
}

type Message<K extends keyof Segments> = {
  [P in K]: Segments[P]
}

type ADT = Message<'MSH' | 'PID'>

const message: ADT
message.MSH //OK