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.
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!
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.
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.
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!
You can define the parameter to be optional with ?
:
interface SomeInterface { SomeMethod(arg1: string, arg2: string, arg3?: boolean); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With