Io-ts: String union io-ts type

Created on 21 Jan 2021  路  2Comments  路  Source: gcanti/io-ts

馃殌 Feature request

type Group = "A" | "B" | "C"

I would like to declare an io-ts type to do runtime checks on a string union type.

I'm not sure if this is already possible with the current implementation of io-ts, so please enlighten me if that's the case

Current Behavior

Group: t.string

Desired Behavior

Group: t.stringUnion(["A", "B", "C")

Your environment

| Software |
| ---------- |
"io-ts": "^2.1.3",
"io-ts-promise": "^2.0.2",
"typescript": "3.9.7"

Most helpful comment

With the experimental API, you can use union and literal:

@DenisFrezzato FYI the experimental D.literal takes one or more literals

import * as D from 'io-ts/Decoder'

const Group = D.literal('A', 'B', 'C')

All 2 comments

With the stable API, you can create a union of literals using keyof. From the readme, documentation.

With the experimental API, you can use union and literal:

const Group = D.union(D.literal('A'), D.literal('B'), D.literal('C'))

With the experimental API, you can use union and literal:

@DenisFrezzato FYI the experimental D.literal takes one or more literals

import * as D from 'io-ts/Decoder'

const Group = D.literal('A', 'B', 'C')
Was this page helpful?
0 / 5 - 0 ratings