io-ts-types
io-ts-types copied to clipboard
Nullable fallback
Consider the following code:
import * as t from 'io-ts';
import { fallback } from 'io-ts-types';
const EnumWithFallback = fallback(t.keyof({ foo: null }))('foo');
const NullableWithEnum = t.partial({
val: EnumWithFallback,
});
console.log(NullableWithEnum.decode({}));
// right({
// "val": "foo"
// })
My goal is to have the last expression evaluate to right({}). In other words, I want to have a fallback type that only falls back if something other than null or undefined is given to it. Is this possible?
@torkelrogstad unfortunately, the combinatorial nature of the implementation prevents that behaviour.
what about
const Nullable = t.union([t.null, t.undefined])
const Enum = fallback(t.keyof({ foo: null }))('foo')
const NullableWithEnum = t.partial({
val: t.union([Nullable, Enum])
})
console.log(NullableWithEnum.decode({})) // right({})
console.log(NullableWithEnum.decode({ val: 'foo' })) // right({ "val": "foo" })
console.log(NullableWithEnum.decode({ val: 'a' })) // right({ "val": "foo" })
console.log(NullableWithEnum.decode({ val: null })) // right({ "val": null })