Last active
January 21, 2021 21:58
-
-
Save attila/060ed1bf14aa86a921d24476e19cefb8 to your computer and use it in GitHub Desktop.
Type assertion / coercion with io-ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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