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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
And beware that if you call SomeMethod('foo','bar') the arg3 parameter will be undefined, and not null.
And also, if you have a optional argument, all following arguments must also be optional. So arg4: boolean is not allowed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.