TypeScript Typed Functions
A typed function states the type of each parameter and the type of the value it returns. The compiler checks every call and every return value against those types.
Types on parameters and the return value
Both parameters take numbers. The function returns a number.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(3, 4));A wrong-type argument is refused
The second parameter takes a number. A string argument fails the check.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(3, "4"));A wrong return value is refused
The return type promises a string. Returning a number fails the check.
function label(count: number): string {
return count;
}
console.log(label(3));A void function returns nothing
A void function does its work inside its own body. This one logs the line itself.
function announce(name: string): void {
console.log("Ready: " + name);
}
announce("Ada");Example
function multiply(a: number, b: number): number {
return a * b;
}
function showTotal(value: number): void {
console.log("Total: " + value);
}
const total: number = multiply(6, 7);
showTotal(total);Key points
- A parameter type follows the parameter name after a colon.
- A return type follows the parameter list after a colon.
- The compiler checks the arguments at each call against the parameter types.
- The compiler checks the returned value against the return type.
- void marks a function that returns no value.
In this example, multiply takes two numbers and returns their product. The product of 6 and 7 is 42. showTotal takes that number and logs it. showTotal returns no value, so its return type is void.
Note
When no return type is written, the compiler works the return type out from the return statement.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
In function add(a: number, b: number): number, what does the final : number state?