F

Functions

Functions in TypeScript can have typed parameters and return types, with support for optional and default parameters.

Code

typescript
1// Basic function with typed parameters and return type
2function add(a: number, b: number): number {
3 return a + b;
4}
5
6// Arrow function syntax
7const multiply = (a: number, b: number): number => a * b;
8
9// Optional parameters (marked with ?)
10function greet(name: string, greeting?: string): string {
11 return `${greeting || "Hello"}, ${name}!`;
12}
13
14// Default parameters
15function createUser(name: string, role: string = "user"): object {
16 return { name, role, createdAt: new Date() };
17}
18
19// Rest parameters
20function sum(...numbers: number[]): number {
21 return numbers.reduce((acc, n) => acc + n, 0);
22}
23
24// Function type annotation
25type MathOperation = (a: number, b: number) => number;
26const subtract: MathOperation = (a, b) => a - b;
27
28console.log(add(5, 3)); // 8
29console.log(multiply(4, 7)); // 28
30console.log(greet("Alice")); // Hello, Alice!
31console.log(greet("Bob", "Hi")); // Hi, Bob!
32console.log(sum(1, 2, 3, 4, 5)); // 15

Run this example locally

$ npx ts-node basics/functions.ts