Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Default parameters on class with interface

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.

like image 432
Grofit Avatar asked Sep 05 '13 15:09

Grofit


People also ask

Can we set default value for TypeScript interface?

To set default values for an interface in TypeScript, create an initializer function, which defines the default values for the type and use the spread syntax (...) to override the defaults with user-provided values. Copied!

How do you give a default parameter value in TypeScript?

Use default parameter syntax parameter:=defaultValue if you want to set the default initialized value for the parameter. Default parameters are optional. To use the default initialized value of a parameter, you omit the argument when calling the function or pass the undefined into the function.

How do you pass an interface as a parameter TypeScript?

An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.

How do you make properties optional in interface TypeScript?

Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!


1 Answers

You can define the parameter to be optional with ?:

interface SomeInterface {      SomeMethod(arg1: string, arg2: string, arg3?: boolean); } 
like image 61
Ryan Cavanaugh Avatar answered Sep 21 '22 04:09

Ryan Cavanaugh