TS TypeScript
Functions
Functions are reusable blocks of code. In TypeScript, you can add types to function parameters and return values, making your functions self-documenting and safer to use.
Basic function syntax
// Type annotations on parameters AND return value
function add(a: number, b: number): number {
return a + b;
}
// TypeScript can also infer the return type
function greet(name: string) {
return `Hello, ${name}!`; // return type inferred as string
}
Arrow functions
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;
// Single-parameter arrow functions
const double = (x: number) => x * 2;
Optional & default parameters
// Optional parameter — marked with ?
function greet(name: string, greeting?: string) {
return `${greeting || "Hello"}, ${name}!`;
}
// Default parameter — uses = to set a default
function greet2(name: string, greeting: string = "Hello") {
return `${greeting}, ${name}!`;
}
greet("Alice"); // "Hello, Alice!"
greet("Alice", "Hi"); // "Hi, Alice!"
Return types
// Explicit return type
function divide(a: number, b: number): number {
return a / b;
}
// Void — function doesn't return anything
function logMessage(msg: string): void {
console.log(msg);
}
// Never — function never returns (throws or loops forever)
function throwError(msg: string): never {
throw new Error(msg);
}
Editor
TypeScript
Console
Quiz
How do you define a function's return type in TypeScript?
Challenge
Write a function called sum that takes two numbers and returns their sum. Add a return type annotation. Then write an arrow function version of the same function.