Skip to content

Instantly share code, notes, and snippets.

@amphineko
Created July 10, 2020 19:58
Show Gist options
  • Save amphineko/1186bf0586a5d4026c0e682724758867 to your computer and use it in GitHub Desktop.
Save amphineko/1186bf0586a5d4026c0e682724758867 to your computer and use it in GitHub Desktop.
io-ts decoding and custom types example
import { either, isLeft, isRight } from 'fp-ts/lib/Either'
import * as it from 'io-ts'
import { Int, Type, TypeOf } from 'io-ts'
import { PathReporter } from 'io-ts/lib/PathReporter'
// custom type: integer string
const IntegerString = new Type<number, string, unknown>(
'IntegerString',
Int.is,
(u, c) =>
either.chain(it.string.validate(u, c), src => {
const out = +src
return Int.is(out) ? it.success(out) : it.failure(u, c, `${src} is not a valid integer`)
}),
String
)
// container type
const Container = it.interface({
integerString: IntegerString,
plainString: it.string
})
// decoding and error reporting
const failedDecode = Container.decode(JSON.parse(JSON.stringify({
integerString: '114.514',
plainString: 'this should fail'
})))
const error = PathReporter.report(failedDecode)[0]
if (isLeft(failedDecode)) {
console.error(error)
} else {
throw new Error('Assertion failed')
}
// static type extraction
const successDecode = Container.decode(JSON.parse(JSON.stringify({
integerString: '-1919810',
plainString: 'this should succeed'
})))
type ContainerT = TypeOf<typeof Container>
function printResult(result: ContainerT) {
console.log(result)
}
if (isLeft(successDecode)) {
throw new Error('Assertion failed')
} else {
printResult(successDecode.right)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment