Typed Functions
Parameter types, return types, optional params, overloads, and function types
Skills taught: ts.typed-parameters, ts.return-types, ts.optional-params, ts.default-params, ts.rest-params, ts.function-types, ts.overloads
Function signatures
// Basic: typed parameters and return type
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const multiply = (a: number, b: number): number => a * b;
// Optional parameter — b may be missing (type: string | undefined)
function greet(name: string, greeting?: string): string {
return `${greeting ?? 'Hello'}, ${name}!`;
}
console.log(greet('Alice')); // Hello, Alice!
console.log(greet('Bob', 'Hey')); // Hey, Bob!
// Default parameter — also optional, but has a fallback
function createUser(name: string, role: string = 'user'): object {
return { name, role };
}
console.log(createUser('Alice')); // { name: 'Alice', role: 'user' }
console.log(createUser('Admin', 'admin')); // { name: 'Admin', role: 'admin' }
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
// Destructured object parameter
function formatUser({ name, age }: { name: string; age: number }): string {
return `${name} (${age})`;
}
console.log(formatUser({ name: 'Alice', age: 30 }));
Function types and overloads
// Function type alias
type Transform = (input: string) => string;
type Predicate<T> = (item: T) => boolean;
const upper: Transform = s => s.toUpperCase();
const isLong: Predicate<string> = s => s.length > 5;
console.log(upper('hello')); // HELLO
console.log(isLong('hi')); // false
console.log(isLong('hello world')); // true
// Higher-order functions with typed callbacks
function filter<T>(arr: T[], predicate: Predicate<T>): T[] {
return arr.filter(predicate);
}
const words = ['hi', 'hello', 'typescript', 'ok'];
console.log(filter(words, isLong));
// Function overloads — different signatures for different inputs
function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number): string | number {
if (typeof input === 'string') return parseInt(input, 10);
return input.toString();
}
console.log(parse('42')); // 42 (number)
console.log(parse(42)); // '42' (string)
// Async function — return type is always Promise<T>
async function fetchData(url: string): Promise<string> {
// Simulated
return `data from ${url}`;
}
fetchData('/api').then(d => console.log(d));
Frequently Asked Questions
When should I annotate the return type vs let TypeScript infer it?
Let TypeScript infer for short, simple functions. Annotate explicitly when: the function is exported (public API), the inferred return type is wider than intended, or the function body is complex enough that a wrong return could be missed. For async functions, always annotate Promise<T> — it documents the resolved type clearly.