I'm trying to make a parameter optional in my function and TypeScript is throwing an error.
Example code:
showDialog(title: string, value: string, callback: Function = null) {
}
Typescript error:
Type 'null' is not assignable to type 'Function'.ts(2322)
Callback is optional. How do I avoid this error?
There's a difference between an optional parameter and a parameter that is potentially null
.
For an optional parameter, implicitly typed as T | undefined
, you would write:
showDialog(title: string, value: string, callback?: Function) {}
Optional parameters have to be placed at the end of the parameter list, i.e. they cannot be followed by required parameters.
For a parameter that can be null
, you would use a union type:
showDialog(title: string, value: string, callback: Function | null) {}
Which you can also give the default value of null
:
showDialog(title: string, value: string, callback: Function | null=null) {}
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