Typed functions
In TypeScript, a function's parameters and its result can all have types:
function add(a: number, b: number): number {
return a + b;
}
add(2, 3); // 5
add(2, "3"); // error: string is not assignable to number
The type after the brackets, : number, is the return type. TypeScript checks that every return matches it, and that callers pass the right things.
Arrow functions work the same way:
const square = (n: number): number => n * n;
Optional and default parameters
A ? makes a parameter optional. Inside the function its type includes undefined, so check before using it:
function greet(name: string, title?: string): string {
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
A default value is used when the caller leaves the argument out, and also tells TypeScript the type:
function repeat(text: string, times: number = 2): string {
return text.repeat(times);
}
A function that returns nothing has the return type void.
Your task
- Write
formatPrice(amount: number, currency: string = "USD"): stringreturning e.g."USD 12.50"(always two decimals:amount.toFixed(2)). - Write
fullName(first, last, middle?)with proper types, returning"Tariro Moyo"or, with a middle name,"Tariro Grace Moyo".