TypeScript Functions
In TypeScript you can give a type to each function parameter and to the value the function returns.
Parameter and Return Types
Example
function multiply(a: number, b: number): number {
return a * b;
}
console.log(multiply(6, 7));
// multiply(6, "7"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'42
a: numberandb: numberare the parameter types: numberafter the brackets is the return type
TypeScript can usually infer the return type, but writing it helps you catch mistakes inside the function.
Wrong Number of Arguments
Unlike JavaScript, TypeScript checks how many arguments you pass:
Example
function greet(name: string): string {
return "Hello " + name;
}
greet(); // Error: Expected 1 arguments, but got 0.
greet("Ali", "Khan"); // Error: Expected 1 arguments, but got 2.Optional Parameters
Add ? after a parameter name to make it optional. Inside the function its type also includes undefined.
Example
function fullName(first: string, last?: string): string {
if (last) {
return first + " " + last;
}
return first;
}
console.log(fullName("Ayesha"));
console.log(fullName("Ayesha", "Malik"));Ayesha Ayesha Malik
Optional parameters must come after required ones.
Default Parameters
A default value makes a parameter optional, and TypeScript infers its type from the value:
Example
function deliveryFee(city: string, express = false): number {
const base = city === "Karachi" ? 150 : 300;
return express ? base * 2 : base;
}
console.log(deliveryFee("Karachi"));
console.log(deliveryFee("Lahore", true));150 600
Rest Parameters
A rest parameter collects any number of arguments into a typed array:
Example
function total(...prices: number[]): number {
return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total(250, 120, 80));450
void Functions
If a function does not return anything, its return type is void:
Example
function logOrder(id: number): void {
console.log(`Order ${id} received`);
}Arrow Functions
Arrow functions are typed the same way:
Example
const square = (n: number): number => n * n;
const isAdult = (age: number): boolean => age >= 18;
console.log(square(9), isAdult(16));81 false
Function Types
You can describe the type of a function itself, for example for a callback:
Example
type PriceRule = (price: number) => number;
const tenPercentOff: PriceRule = p => p * 0.9;
const flatOff: PriceRule = p => p - 200;
function applyRule(price: number, rule: PriceRule): number {
return rule(price);
}
console.log(applyRule(2000, tenPercentOff));
console.log(applyRule(2000, flatOff));1800 1800
Notice that p needs no annotation inside the arrow functions. TypeScript knows it is a number from the PriceRule type.
| Syntax | Meaning |
|---|---|
(x: number) | Required parameter |
(x?: number) | Optional parameter |
(x = 5) | Default value, type inferred |
(...x: number[]) | Rest parameter |
(): void | Returns nothing |
(n: number) => string | A function type |
Turn on "strict": true in tsconfig.json. Then TypeScript also warns you about parameters with no type, instead of silently treating them as any.
Exercise
Exercise
How do you mark the parameter phone as optional?
