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

Union type #425

Open
shimataro opened this issue Feb 15, 2020 · 1 comment · May be fixed by #438
Open

Union type #425

shimataro opened this issue Feb 15, 2020 · 1 comment · May be fixed by #438

Comments

@shimataro
Copy link
Owner

shimataro commented Feb 15, 2020

Like this:

import assert from "assert";
import vs from "value-schema";

// accepts both number and integer
const schema = vs.union({
    schemas: [vs.number(), vs.string()],
});

assert.strictEqual(schema.applyTo(1), 1);
assert.strictEqual(schema.applyTo("a"), "a");
@shimataro shimataro linked a pull request Feb 19, 2020 that will close this issue
@shimataro
Copy link
Owner Author

interface

const schema = vs.union(vs.number(), vs.string());
assert.strictEqual(schema.applyTo(1), 1);

examples

// should be OK
assert.strictEqual(
    vs.union(vs.number(), vs.string()).applyTo(1),
    1);
assert.strictEqual(
    vs.union(vs.number(), vs.string()).applyTo("a"),
    "a");

// should be adjusted
assert.strictEqual(
    vs.union(vs.number(), vs.string()).applyTo("1"),
    1);
assert.strictEqual(
    vs.union(vs.string(), vs.number()).applyTo("1"), // this won't be adjusted. be careful of schemas order!
    "1");

// should cause error
assert.throws(
    () => vs.union(vs.number(), vs.string()).applyTo({}),
    {name: "ValueSchemaError", cause: vs.CAUSE.TYPE});

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

Successfully merging a pull request may close this issue.

1 participant