In TypeScript, you can set default parameter values for a function by providing a default value for each parameter. To do this, you add an equals sign (=) followed by the default value after the parameter declaration. For example:
index.ts151 chars7 lines
In the example above, the greet
function takes a parameter name
which has a default value of 'World'
. This means that if the name
parameter is not provided when the greet
function is called, the default value 'World'
will be used.
You can also combine default parameters with optional parameters, like this:
index.ts229 chars8 lines
In the example above, the greet
function takes two parameters, name
and greeting
. The name
parameter is optional, indicated by the ?
after the parameter name. The greeting
parameter has a default value of 'Hello'
. If name
is not provided, the string 'World'
is used instead. If greeting
is not provided, the default value 'Hello'
is used.
With default parameters, you can reduce the boilerplate code required to check for the existence of a parameter and provide a default value if it doesn't exist.
gistlibby LogSnag