Function signatures
Let's look at how we can add explicit types to our function signatures.
Parameter types
To add types to your parameter list, simply add annotate the parameter with : {type}.
For example:
function add(x: number, y: number) {
return x + y;
}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.
Return type
To add a return type, simply add : {type} after the () of your parameter declarations.
For example:
function add(x: number, y: number): number {
return x + y;
}Now it's very clear that this function returns a number and only a number.
If you don't have an explicit return, use void.
Optional parameters
TypeScript supports optional parameters.
To mark a parameter as optional, simply append a ? to the parameter's name.
For example:
function foo(bar: number, baz?: string): void {
// ...
}
foo(123); // OK
foo(123, 'hello'); // OK
foo(123, 123); // Error: 2nd parameter not of type 'string'.
foo(123, 'hello', 'extra param'); // Error: expected 1-2 arguments, but got 3.Default parameters
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:
function logGreeting(greeting: string = 'Hello!'): void {
console.log(greeting);
}
logGreeting(); // logs "Hello!"
logGreeting('Oi como vai!'); // logs "Oi como vai!"Last updated