grian
grian

Reputation: 318

How to use default parameter values when extending prototype in typescript?

If I have this code

declare global {
    interface Number {
        foo(bool: boolean): number;
    }
}

Number.prototype.foo = function (bool: boolean = false) {
    if (bool) {
        return 0;
    } else {
        return this.valueOf();
    }
}

export {};

(100).foo();

tsc tells me that it's missing the bool argument for (100).foo(), even though I set a default in the function definition.

I'm not sure what I'm doing wrong here.

Typescript playground link with the above code here.

Upvotes: 0

Views: 172

Answers (2)

ABOS
ABOS

Reputation: 3823

Alternatively, you can

declare global {
    interface Number {
        foo(): number;
        foo(bool: boolean): number;
    }
}

Upvotes: 0

Aplet123
Aplet123

Reputation: 35560

The fact that there's a default argument is not expressed in the typing. You should do so with a question mark to denote an optional argument:

declare global {
    interface Number {
        foo(bool?: boolean): number;
    }
}

See also:

Upvotes: 3

Related Questions