Typed Functions
Parameter types, return types, optional and default parameters, and function type signatures
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
TypeScript lets you annotate every parameter and the return value of a function. The compiler then catches wrong arguments and wrong uses of the return value.
Basic parameter and return type annotations:
typescript function add(a: number, b: number): number { return a + b; } // Arrow function equivalent const add = (a: number, b: number): number => a + b; // TypeScript infers the return type — explicit annotation is optional when obvious function greet(name: string) { // return type inferred as string return Hello, ${name}!; }
Optional parameters — suffix with ?: ``typescript function greet(name: string, greeting?: string): string { return ${greeting ?? 'Hello'}, ${name}!; } greet('Alice'); // "Hello, Alice!" greet('Alice', 'Hey'); // "Hey, Alice!"
Default parameters:
typescript function greet(name: string, greeting = 'Hello'): string { return ${greeting}, ${name}!; } // TypeScript infers greeting's type as string from the default value
Rest parameters:
typescript function sum(...nums: number[]): number { return nums.reduce((total, n) => total + n, 0); } sum(1, 2, 3, 4); // 10
Function types — describe function shapes: ``typescript // A variable that holds a function let transform: (value: string) => string; transform = (s) => s.toUpperCase(); // OK // transform = (n: number) => n * 2; // Error // In an interface interface Calculator { add(a: number, b: number): number; subtract(a: number, b: number): number; }
Overloads — one implementation, multiple typed call signatures: ``typescript function format(val: string): string; function format(val: number): string; function format(val: string | number): string { return String(val).trim(); } // format(true); // Error — boolean doesn't match either overload
Examples
Typed parameters and return values
Default parameters implicitly make the parameter optional. Optional (`?`) parameters default to `undefined`. Both appear after required parameters.
// All parameters and return type annotated
function divide(a: number, b: number): number {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
// Optional + default parameters
function createUser(name: string, role = 'user', active?: boolean) {
return {
name,
role, // type inferred as string
active: active ?? true, // defaults to true if not provided
};
}
const admin = createUser('Alice', 'admin');
const guest = createUser('Bob');
console.log(admin); // { name: 'Alice', role: 'admin', active: true }
console.log(guest); // { name: 'Bob', role: 'user', active: true }
// TypeScript catches wrong argument types
// divide('10', 2); // Error: Argument of type 'string' is not assignable to parameter of type 'number'Function types and callbacks
Function types are first-class in TypeScript — you can type callbacks, higher-order functions, and factories with the same precision as any other value.
// Function type as a variable
type Transformer = (value: string) => string;
const upper: Transformer = (s) => s.toUpperCase();
const trim: Transformer = (s) => s.trim();
// Accepting a function type as a parameter (callback)
function process(values: string[], fn: Transformer): string[] {
return values.map(fn);
}
console.log(process([' hello ', ' world '], trim));
// ['hello', 'world']
// Returning a function
function multiplier(factor: number): (n: number) => number {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15How well did you understand this?
Next in TypeScript
Generics