Function signatures
Last updated
Last updated
Let's look at how we can add explicit types to our function signatures.
To add types to your parameter list, simply add annotate the parameter with : {type}
.
For example:
Here TypeScript is actually able to infer that the return type is number
. Smart! However, we want to be explicit about the return type, so let's annotate it.
To add a return type, simply add : {type}
after the ()
of your parameter declarations.
For example:
Now it's very clear that this function returns a number
and only a number
.
If you don't have an explicit return, use .
TypeScript supports optional parameters.
To mark a parameter as optional, simply append a ?
to the parameter's name.
For example:
Additionally, you can provide a default value (using = someValue
after the parameter declaration) which will get assigned if the caller doesn't provide that argument.
For example: