Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nullable fallback #66

Open
torkelrogstad opened this issue Oct 10, 2018 · 2 comments
Open

Nullable fallback #66

torkelrogstad opened this issue Oct 10, 2018 · 2 comments

Comments

@torkelrogstad
Copy link

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?

@sledorze
Copy link
Collaborator

sledorze commented Nov 23, 2018

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

@gcanti
Copy link
Owner

gcanti commented Jun 21, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants