Typescript - Default parameters on class with interface

37,556

You can define the parameter to be optional with ?:

interface SomeInterface {
     SomeMethod(arg1: string, arg2: string, arg3?: boolean);
}
Share:
37,556
Grofit
Author by

Grofit

Updated on July 09, 2022

Comments

  • Grofit
    Grofit almost 2 years

    I have a scenario where I have an interface which has a method like so:

    interface SomeInterface
    {
       SomeMethod(arg1: string, arg2: string, arg3: boolean);
    }
    

    And a class like so:

    class SomeImplementation implements SomeInterface
    {
       public SomeMethod(arg1: string, arg2: string, arg3: boolean = true){...}
    }
    

    Now the problem is I cannot seem to tell the interface that the 3rd option should be optional or have a default value, as if I try to tell the interface there is a default value I get the error:

    TS2174: Default arguments are not allowed in an overload parameter.

    If I omit the default from the interface and invokes it like so:

    var myObject = new SomeImplementation();
    myObject.SomeMethod("foo", "bar");
    

    It complains that the parameters do not match any override. So is there a way to be able to have default values for parameters and inherit from an interface, I dont mind if the interface has to have the value as default too as it is always going to be an optional argument.

  • Grofit
    Grofit almost 11 years
    oh I thought this was removed in favor of the default value in one of the recent versions. So I am able to use the optional argument in the interface and default value argument in the class?
  • Ryan Cavanaugh
    Ryan Cavanaugh almost 11 years
    You can still use optional arguments without defaults anywhere. The only disallowed thing is the redundant syntax x ?= 4 -- you can either have the ? or the default value.
  • vegemite4me
    vegemite4me over 10 years
    And beware that if you call SomeMethod('foo','bar') the arg3 parameter will be undefined, and not null.
  • pensan
    pensan over 5 years
    And also, if you have a optional argument, all following arguments must also be optional. So arg4: boolean is not allowed.