Search code examples
typescriptinterfacedefault-parameters

Is it possible to provide default parameter to interface function in typescript?


I extend the Number class as follows:

interface Number {
    evolution(now: number, before: number): string;
}


Number.prototype.magnitude = function(d=1, suffix="") {
    //…
}

And I like to provide default parameters.

But when using it with no explicit parameter ass follows:

label = "÷ " + show.magnitude();

I got an error "The supplied parameters do not match signature"


Solution

  • You need to tell the TypeScript compiler that the parameters are optional:

    In JavaScript, every parameter is optional, and users may leave them off as they see fit. When they do, their value is undefined. We can get this functionality in TypeScript by adding a ? to the end of parameters we want to be optional.

    Here is an example similar to what you want to accomplish:

    interface ISum {
        (baz?: number, buz?: number): number;
    }
    
    let sum: ISum = (baz = 1, buz = 2) => {
        return baz + buz;
    }
    
    console.log(sum()); //Console: 3
    console.log(sum(2)); //Console: 4
    console.log(sum(2, 7)); //Console: 9