Episode 8 of 21
Function Basics
Typed function parameters, return types, and optional parameters in TypeScript.
Function Basics
Functions in TypeScript can have typed parameters and typed return values.
Typed Parameters
const greet = (name: string, age: number) => {
console.log(`Hello ${name}, you are ${age}`);
};
greet("Mario", 30); // ✅
greet("Mario"); // ❌ Expected 2 arguments
greet("Mario", "30"); // ❌ Argument of type 'string' not assignable
Return Types
TypeScript infers return types, but you can be explicit:
const add = (a: number, b: number): number => {
return a + b;
};
// void — function doesn't return anything
const log = (message: string): void => {
console.log(message);
};
Optional Parameters
const greet = (name: string, greeting?: string) => {
console.log(`${greeting || "Hello"}, ${name}`);
};
greet("Mario"); // "Hello, Mario"
greet("Mario", "Hi"); // "Hi, Mario"
Default Parameters
const add = (a: number, b: number = 10): number => {
return a + b;
};
add(5); // 15
add(5, 3); // 8
Key Takeaways
- Add types to parameters:
(name: string) - Add return types:
(): number - Use
voidfor functions with no return - Optional params use
?suffix