Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Assert structure with optional fields and disallow unknown fields #9

Open
robianmcd opened this issue Dec 5, 2014 · 0 comments
Open

Comments

@robianmcd
Copy link

Is there an easy way to assert a structure that has some required fields and some optional fields. And have it fail if there are any other unknown fields.

This works but I'm just wondering if there is a better way:

export default class Directive {
    constructor(options: DirectiveOptions) {
        this.selector = options.selector;
        this.bind = options.bind;
    }
}

var DirectiveOptions = assert.define('DirectiveOptions', function(options) {
    //Required fields
    assert(options).is(assert.structure({
        selector: assert.string
    }));

    //Optional fields
    if(options.bind) {
        assert.type(options.bind, Object);
    }

    for(var key in options) {
        if (options.hasOwnProperty(key)) {
            if(key !== 'selector' && key !== 'bind') {
                assert.fail(`${key} is not a valid directive field`);
            }
        }
    }
});

On an unrelated note any idea what I need to use assert.string instead of just string. I'm transpiling with Traceur 0.0.74.

Thanks

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

No branches or pull requests

1 participant