【问题标题】:How to define mixed array in io-ts?如何在 io-ts 中定义混合数组?
【发布时间】:2020-04-30 22:20:09
【问题描述】:

使用最新的https://github.com/gcanti/io-ts/,我想将NodeLsStatusResponse 的属性result 建模为在(t.readonlyArray) 中包含NodeStatusNodeStatus404 类型的对象

io-ts这个关系怎么定义?

export const Connection = t.union([t.literal('a'), t.literal('b')])
export type Connection = t.TypeOf<typeof Connection>

export const NodeStatus = t.type({
  connection: Connection,
  nodeId: t.string,
})

export const NodeStatus404 = t.type({
  connection: Connection,  
  host: t.string,
})

export type NodeStatus = t.TypeOf<typeof NodeStatus>
export type NodeStatus404 = t.TypeOf<typeof NodeStatus404>

export const NodeLsStatusResponse = t.type({
  code: t.literal('OK'),
  result: t.readonlyArray(NodeStatus), /// <<< I would like to have a mixed array here
})

【问题讨论】:

  • t.readonlyArray(NodeStatus | NodeStatus404 ) 怎么样?
  • 我试过没用

标签: typescript fp-ts


【解决方案1】:

我能够通过对只读数组使用联合来解决这个问题:

export const NodeLsStatusResponse = t.type({
  code: t.literal('OK'),
  result: t.readonlyArray(t.union([NodeStatus, NodeStatus404])),
})

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 2021-09-18
    • 2021-10-27
    • 2018-03-11
    • 2011-02-03
    • 2020-07-13
    • 1970-01-01
    • 2021-05-04
    • 2012-01-31
    相关资源
    最近更新 更多