io-ts-types icon indicating copy to clipboard operation
io-ts-types copied to clipboard

Nullable fallback

Open torkelrogstad opened this issue 7 years ago • 2 comments

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 avatar Oct 10 '18 09:10 torkelrogstad

@torkelrogstad unfortunately, the combinatorial nature of the implementation prevents that behaviour.

sledorze avatar Nov 23 '18 20:11 sledorze

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 })

gcanti avatar Jun 21 '19 14:06 gcanti