user3568783
user3568783

Reputation:

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?

Upvotes: 0

Views: 150

Answers (1)

basarat
basarat

Reputation: 276171

Use = defaultValue i.e

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);
        });
    }

Upvotes: 1

Related Questions