50

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.

1 Answer 1

79

You can define the parameter to be optional with ?:

interface SomeInterface {
     SomeMethod(arg1: string, arg2: string, arg3?: boolean);
}
4
  • 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?
    – Grofit
    Commented Sep 6, 2013 at 7:34
  • 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. Commented Sep 6, 2013 at 14:38
  • 10
    And beware that if you call SomeMethod('foo','bar') the arg3 parameter will be undefined, and not null. Commented Jan 28, 2014 at 17:38
  • And also, if you have a optional argument, all following arguments must also be optional. So arg4: boolean is not allowed.
    – pensan
    Commented Feb 17, 2019 at 13:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.