📘
Typed Functions and Arrow Functions
Beginner
90 XP
35 min
Lesson Content
Typed Functions in TypeScript
Functions in TypeScript can have typed parameters and return values, making them more predictable and easier to use.
Function Declarations
function add(a: number, b: number): number {
return a + b;
}Arrow Functions
const multiply = (a: number, b: number): number => {
return a * b;
};
// Shorthand
const divide = (a: number, b: number): number => a / b;Optional Parameters
function greet(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}`;
}
return `Hello, ${name}`;
}Default Parameters
function createUser(name: string, age: number = 18): object {
return { name, age };
}Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}Example Code
Practice writing typed functions
// Regular function
function greet(name: string): string {
return `Hello, ${name}!`;
}
// Arrow function
const calculate = (x: number, y: number): number => x + y;
// With default parameter
function createMessage(text: string, prefix: string = "Info"): string {
return `[${prefix}] ${text}`;
}
console.log(greet("TypeScript"));
console.log(calculate(5, 3));
console.log(createMessage("Learning TypeScript"));Expected Output:
Hello, TypeScript! 8 [Info] Learning TypeScript
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code