Typing Functions in TypeScript
Typing Functions
~17 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
Functions are the heart of every program – this chapter covers ALL aspects of typing functions in TypeScript: parameters, return values, optional and default parameters, rest parameters, and function overloads.
Parameter and return type
function calculateYearsSincePublication(publicationYear: number): number {
const currentYear = new Date().getFullYear();
return currentYear - publicationYear;
}
calculateYearsSincePublication(1954); // ✓ correct
calculateYearsSincePublication('1954'); // ✗ error: string not assignable to numberpublicationYear: number is the parameter annotation, ): number AFTER the parentheses is the return type. As explained in chapter 5: parameters MUST be annotated (TypeScript can't infer them), the return type is technically inferable, but specifying it explicitly is good style.
void: functions with no return value
function logCheckout(title: string): void {
console.log(`"${title}" was checked out.`);
// no return - void fits
}void from chapter 4 in practice: a function that ONLY has a side effect (here: console output) and returns nothing meaningful.
Optional parameters with ?
function formatBookTitle(title: string, subtitle?: string): string {
if (subtitle) {
return `${title}: ${subtitle}`;
}
return title;
}
formatBookTitle('The Lord of the Rings'); // ✓ subtitle omitted
formatBookTitle('The Lord of the Rings', 'The Fellowship of the Ring'); // ✓ with subtitleAchtung: Optional parameters (?) MUST come after all required parameters – function f(a?: string, b: number) is an error. Inside the function, subtitle has the type string | undefined (a preview of chapter 9), not simply string – that's why the if (subtitle) check is needed before treating the value as a guaranteed string.
Default parameters
function createBookList(count: number = 10): string[] {
return Array.from({ length: count }, (_, i) => `Book ${i + 1}`);
}
createBookList(); // uses the default: 10
createBookList(3); // overrides the default: 3Unlike optional parameters (string | undefined), count HERE has the clean type number – TypeScript knows the default is substituted automatically when omitted, so the value is NEVER undefined inside the function.
Rest parameters: any number of arguments
function collectGenres(...genres: string[]): string[] {
return [...new Set(genres)]; // remove duplicates
}
collectGenres('Fantasy', 'Adventure', 'Fantasy'); // ['Fantasy', 'Adventure']...genres: string[] collects ANY number of arguments into a single array – every individual argument must match the element type (string).
Function types as a standalone type
type CompareFunction = (a: string, b: string) => number;
const alphabetical: CompareFunction = (a, b) => a.localeCompare(b);
// parameters a/b need no annotation of their own HERE - TypeScript infers them
// from the CompareFunction type ("contextual typing")type CompareFunction = (a: string, b: string) => number describes the SHAPE of a function (which parameters, which return type), without implementing it – useful for callback parameters (see Array.prototype.sort-style patterns), explored further in chapter 8 (type aliases).
In practice: a first book search function
interface SimpleBook {
title: string;
author: string;
publicationYear: number;
}
// 'interface' gets explained in detail in chapter 7 - used here as a preview
// to demonstrate a meaningful book search
const books: SimpleBook[] = [
{ title: 'The Lord of the Rings', author: 'J.R.R. Tolkien', publicationYear: 1954 },
{ title: '1984', author: 'George Orwell', publicationYear: 1949 },
{ title: 'The Hobbit', author: 'J.R.R. Tolkien', publicationYear: 1937 },
];
function searchByAuthor(books: SimpleBook[], author: string): SimpleBook[] {
return books.filter((book) => book.author === author);
}
const tolkienBooks = searchByAuthor(books, 'J.R.R. Tolkien');
console.log(`${tolkienBooks.length} books by Tolkien found:`);
tolkienBooks.forEach((book) => console.log(`- ${book.title} (${book.publicationYear})`));Tipp: Rule of thumb for function signatures: the more precise the parameter and return types, the better the autocompletion AND the sooner you'll notice even typos yourself – searchByAuthor(books, 'j.r.r. tolkien') (lowercase) wouldn't trigger a TYPE error HERE (both are string), but would return an empty result – a good moment to emphasize: types prevent TYPE errors, not LOGIC errors.