简体   繁体   中英

How can I deal with optional function parameters with Typescript?

I defined a function like this in Javascript:

 checkButton (elem, expectedPresent, expectedEnabled) {
        var id = elem.locator_.value;
        var title = this.getTitle(id);
        expectedPresent = typeof expectedPresent !== 'undefined' ? expectedPresent : true;
        expectedEnabled = typeof expectedEnabled !== 'undefined' ? expectedEnabled : true;
        var enabledCheck = expectedEnabled ? "enabled" : "disabled";
        it(title + ' - Check it is ' + enabledCheck, function () {
            expect(elem.isPresent()).toBe(expectedPresent);
            expect(elem.isEnabled()).toBe(expectedEnabled);
        });
    }

The two trailing parameters are optional.

Now I am using Typescript. Can someone tell me if there is a better way for me to define these optional parameters using Typescript. Also how should I set the arguments so that Typescript will not give a syntax error in the call to this function when the params are not present?

Use = defaultValue ie

checkButton (elem, expectedPresent = true , expectedEnabled = true ) {
        var id = elem.locator_.value;
        var title = this.getTitle(id);
        var enabledCheck = expectedEnabled ? "enabled" : "disabled";
        it(title + ' - Check it is ' + enabledCheck, function () {
            expect(elem.isPresent()).toBe(expectedPresent);
            expect(elem.isEnabled()).toBe(expectedEnabled);
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM