Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a parameter typed but optional in TypeScript

Tags:

typescript

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?

like image 647
1.21 gigawatts Avatar asked Oct 15 '25 04:10

1.21 gigawatts


1 Answers

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) {}
like image 97
Robby Cornelissen Avatar answered Oct 18 '25 10:10

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!