io ts, check if a string is in a union

297 Views Asked by At

Let's say I have the following io-ts runtimetype:

    const Example = t.keyof({
         'foo': null,
         'bar': null
    })
    type ExampleType = typeof Example

And I have an incoming request with value: string

How can I convert value to an Example (or fail and throw an exception?)

1

There are 1 best solutions below

0
On

Functional programming isn't my strong suit, but this should get you going.

import * as t from 'io-ts';
import { pipe } from 'fp-ts/function';
import { fold } from 'fp-ts/Either';

const Example = t.keyof({
  foo: null,
  bar: null,
});
type ExampleType = typeof Example;

function toExample(value: string) {
  const exampleE = Example.decode(value);
  const example = pipe(
    exampleE,
    fold(
      (errors) => {
        const reason = errors
          .map((error) => `"${error.value}" does not match ${Example.name}`)
          .join('\n');
        throw new Error(reason);
      },
      (value) => value
    )
  );
  return example;
}

const example = toExample('foo');
console.log('value=', example);

// Will throw error
const example2 = toExample('bad');