Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.
This repository was 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

Description

@robianmcd

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions