0

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?)

Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • Check out the example in the third code block here: https://github.com/gcanti/io-ts/blob/dedb64e05328417ecd3d87e00008d9e72130374a/index.md. – Dogbert Apr 25 '23 at 12:16

1 Answers1

0

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');
Sly_cardinal
  • 12,270
  • 5
  • 49
  • 50