Lesson 3 of 15
Function Types
Function Types
TypeScript lets you annotate function parameters and return types:
function add(a: number, b: number): number {
return a + b;
}
a: number— parameteramust be a numberb: number— parameterbmust be a number: numberafter the parentheses — the function returns a number
TypeScript verifies the return statement matches the declared return type:
function greet(name: string): string {
return 42; // Error: 'number' is not assignable to type 'string'
}
void
Functions that do not return a value have return type void:
function log(message: string): void {
console.log(message);
}
Function Types as Values
Arrow functions can also be typed:
const multiply = (a: number, b: number): number => a * b;
Optional Parameters
Mark a parameter with ? to make it optional. Optional parameters must come after required ones:
function greet(name: string, greeting?: string): string {
return (greeting || "Hello") + ", " + name;
}
greet("Alice"); // "Hello, Alice"
greet("Alice", "Howdy"); // "Howdy, Alice"
Inside the function, an optional parameter has type T | undefined.
Rest Parameters
Use ...args: T[] to accept any number of arguments of the same type:
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6
sum(10, 20); // 30
Rest parameters must be the last parameter and collect all remaining arguments into an array.
Your Task
- Write
function clamp(n: number, min: number, max: number): numberthat returnsnif it is betweenminandmax,minif it is below, andmaxif it is above. - Write
function joinWords(separator: string, ...words: string[]): stringthat joins all words using the separator.
TypeScript loading...
Loading...
Click "Run" to execute your code.