Functions
Functions are the building blocks of readable, maintainable code. In TypeScript, functions can be typed for parameters and return values, providing better safety and documentation.
Basic Function Syntax
Here's how you define a simple function in TypeScript:
function greet(): void {
console.log("Hello, TypeScript!");
}
greet();
Functions with Parameters
Functions can take typed parameters:
function greetPerson(name: string): void {
console.log(`Hello, ${name}!`);
}
greetPerson("Alice");
Return Types
Functions can return values with explicit type annotations:
function add(x: number, y: number): number {
return x + y;
}
const result = add(5, 3);
console.log(`5 + 3 = ${result}`);
Optional Parameters
Parameters can be made optional using the ? operator:
function buildName(firstName: string, lastName?: string): string {
if (lastName) {
return `${firstName} ${lastName}`;
}
return firstName;
}
console.log(buildName("Alice"));
console.log(buildName("Bob", "Smith"));
Default Parameters
You can provide default values for parameters:
function greetWithDefault(name: string = "Guest"): void {
console.log(`Hello, ${name}!`);
}
greetWithDefault();
greetWithDefault("Alice");
Arrow Functions
Arrow functions provide a concise syntax for writing functions:
// Regular function
function multiply(a: number, b: number): number {
return a * b;
}
// Arrow function
const multiplyArrow = (a: number, b: number): number => {
return a * b;
};
// Concise arrow function (implicit return)
const multiplyShort = (a: number, b: number): number => a * b;
console.log(`multiply(5, 3) = ${multiply(5, 3)}`);
console.log(`multiplyArrow(5, 3) = ${multiplyArrow(5, 3)}`);
console.log(`multiplyShort(5, 3) = ${multiplyShort(5, 3)}`);
Function Types
You can define types for functions:
// Function type
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (a, b) => a + b;
const subtract: MathOperation = (a, b) => a - b;
console.log(`10 + 5 = ${add(10, 5)}`);
console.log(`10 - 5 = ${subtract(10, 5)}`);
Rest Parameters
Functions can accept a variable number of arguments:
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(`sum(1, 2, 3) = ${sum(1, 2, 3)}`);
console.log(`sum(1, 2, 3, 4, 5) = ${sum(1, 2, 3, 4, 5)}`);
Generic Functions
Generics allow you to write reusable functions that work with different types:
// Generic function
function identity<T>(arg: T): T {
return arg;
}
const numberResult = identity<number>(42);
const stringResult = identity<string>("Hello");
console.log(`Number identity: ${numberResult}`);
console.log(`String identity: ${stringResult}`);
// TypeScript can infer the generic type
const inferredNumber = identity(42);
const inferredString = identity("Hello");
console.log(`Inferred number: ${inferredNumber}`);
console.log(`Inferred string: ${inferredString}`);
Try It Yourself
Practice writing functions in the playground below:
// Basic function
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("TypeScript"));
// Function with multiple parameters
function calculateRectangleArea(width: number, height: number): number {
return width * height;
}
console.log(`Area of 5x3 rectangle: ${calculateRectangleArea(5, 3)}`);
// Arrow function
const double = (n: number): number => n * 2;
console.log(`double(21) = ${double(21)}`);
// Function with optional parameter
function createGreeting(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(createGreeting("Alice"));
console.log(createGreeting("Smith", "Dr."));
// Function with default parameter
function power(base: number, exponent: number = 2): number {
return Math.pow(base, exponent);
}
console.log(`3^2 = ${power(3)}`);
console.log(`2^3 = ${power(2, 3)}`);
// Rest parameters
function average(...numbers: number[]): number {
const sum = numbers.reduce((total, n) => total + n, 0);
return sum / numbers.length;
}
console.log(`Average of 10, 20, 30: ${average(10, 20, 30)}`);
Try these exercises:
- Create a function that takes two strings and returns them concatenated
- Write an arrow function that calculates the area of a circle
- Create a function with an optional parameter for a discount percentage
- Write a function using rest parameters to find the maximum number
- Create a generic function that returns the first element of an array
Key Takeaways
- Functions can have typed parameters and return types
- Use
?for optional parameters and=for default values - Arrow functions provide concise syntax
- Rest parameters allow variable-length argument lists
- Generics enable reusable, type-safe functions
- TypeScript infers return types, but explicit types improve clarity
Pro Tip: Start by writing your functions with explicit type annotations. As you become more comfortable, you can rely on TypeScript's type inference for simpler cases!