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

Cannot use types.custom as part of a types.union #736

Closed
univerio opened this issue Mar 28, 2018 · 0 comments
Closed

Cannot use types.custom as part of a types.union #736

univerio opened this issue Mar 28, 2018 · 0 comments

Comments

@univerio
Copy link
Contributor

univerio commented Mar 28, 2018

As demonstrated by the following example, changing a types.union(types.null, types.custom) field from null to a value of the custom type silently fails.

import {types} from "mobx-state-tree";

const customString = types.custom<string, string>({
  name: "custstring",
  fromSnapshot(s: string) {
    return s;
  },
  toSnapshot(s: string) {
    return s;
  },
  isTargetType(v: any) {
    return typeof v === "string";
  },
  getValidationMessage(s: any) {
    if (typeof s !== "string") {
      return "Invalid string";
    }
    return "";
  },
});

const Foo = types.model({
  foo: types.union(types.null, customString),
  bar: types.union(types.null, types.string),
}).actions((self) => ({
  set(s: string | null) {
    self.foo = s;
    self.bar = s;
  },
}));

let foo = Foo.create({foo: null, bar: null});
console.log(foo.foo, foo.bar);  // null null
foo.set("foo");
console.log(foo.foo, foo.bar);  // null 'foo'  <---------------------

foo = Foo.create({foo: "foo", bar: "foo"});
console.log(foo.foo, foo.bar);  // 'foo' 'foo'
foo.set("bar");
console.log(foo.foo, foo.bar);  // 'bar' 'bar'
foo.set(null);
console.log(foo.foo, foo.bar);  // null 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

1 participant