assert icon indicating copy to clipboard operation
assert copied to clipboard

Assert structure with optional fields and disallow unknown fields

Open robianmcd opened this issue 11 years ago • 0 comments

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

robianmcd avatar Dec 05 '14 01:12 robianmcd