I'm currently using PathReporter as follows:
const decoded = MyType.decode(myInput);
if (decoded.isLeft()) {
throw PathReporter.report(decoded).join('\n');
}
return decoded.value;
I would like to replace it with ThrowReporter, using it as:
const decoded = MyType.decode(myInput);
ThrowReporter.report(decoded);
return decoded.value
however ThrowReporter.report doesn't refine the type of decoded, so I can't access .value.
Any suggestion on how to return a value after running ThrowReporter?
I ran into this too. This looks more like a limitation of TypeScript's type guards than anything else. Unfortunately asserting anything about the type of decoded during the call to Reporter.report would imply returning a boolean value from Reporter.report. That runs counter to the signature provided for Reporter.report, Reporter<A>.report(v: Validation<any>) => A.
I could be wrong, but it looks like the best option is to right your own utility to do this. I use:
import { either } from 'fp-ts'
import * as t from 'io-ts';
import { ThrowReporter } from 'io-ts/lib/ThrowReporter'
export function checkValidity<A>(validate: either.Either<t.Errors, A>): validate is either.Right<t.Errors, A> {
ThrowReporter.report(validate);
return true;
}
That said, I still need to help tsc along and tell it that an exception would be thrown in the path where checkValidity would have thrown.
Maybe something like unsafeGet
import { failure } from 'io-ts/lib/PathReporter'
export const unsafeGet = <I, A>(value: I, type: t.Decoder<I, A>): A =>
type.decode(value).getOrElseL(errors => {
throw new Error(failure(errors).join('\n'))
})
Why there isn't something as simple as getOrThrow provided out of the box? ThrowReporter is just silly - no type-checks and more lines of code. Throwing exceptions is the most common way to deal with errors.
ThrowReporter is just silly
I agree, ThrowReporter is deprecated in 1.5 and will be removed in 2.0
Most helpful comment
Why there isn't something as simple as
getOrThrowprovided out of the box?ThrowReporteris just silly - no type-checks and more lines of code. Throwing exceptions is the most common way to deal with errors.