How to define mixed array in io-ts?

2.9k Views Asked by At

Using latest io-ts, I would like to model property result of NodeLsStatusResponse to contains objects of type NodeStatus or NodeStatus404 in (t.readonlyArray)

How to define this relationship with 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
})
1

There are 1 best solutions below

0
On BEST ANSWER

I was able to solve this issue by using an union for the readonly array as:

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