Skip to content

Instantly share code, notes, and snippets.

@attila
Last active January 21, 2021 21:58
Show Gist options
  • Save attila/060ed1bf14aa86a921d24476e19cefb8 to your computer and use it in GitHub Desktop.
Save attila/060ed1bf14aa86a921d24476e19cefb8 to your computer and use it in GitHub Desktop.
Type assertion / coercion with io-ts
import * as D from "io-ts/Decoder";
import { extract } from "fp-ts/lib/Identity";
import { fold } from "fp-ts/lib/Either";
import { pipe } from "fp-ts/lib/function";
// Utility to assert/coerce type.
export const decodeType = <P>(type: D.Decoder<unknown, P>, value: unknown): P =>
pipe(
type.decode(value),
fold(() => {
throw new TypeError("Invalid input");
}, extract)
);
// Example interface
interface FooBar {
id: number;
}
// Decoder for above interface
const TFooBar = D.type({
id: D.number,
});
const getStuff = (input: { [key: string]: unknown }): FooBar => {
// Do computation
const result = { ...input };
return decodeType<FooBar>(TFooBar, result);
};
// This will throw
getStuff({ id: "42" });
// This will return a FooBar
getStuff({ id: 42 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment