BeginnerLesson 3 of 15
Typing Functions – TypeScript
Parameters, return types, optional arguments and function types.
Parameters get types, and the return type goes after the parameter list. The return type can usually be inferred – but for exported functions people like to write it out anyway, as a contract.
function addiere(a: number, b: number): number {
return a + b;
}
const multipliziere = (a: number, b: number): number => a * b;
console.log(addiere(2, 3), multipliziere(4, 5));
// addiere(2); // Error: Expected 2 arguments, but got 1.
// addiere(2, "3"); // Error: string is not numberOptional parameters get a ?, default values infer the type on their own, and rest parameters are arrays:
function begruesse(name: string, gruss = "Hello", zusatz?: string): string {
const text = gruss + ", " + name + "!";
return zusatz ? text + " " + zusatz : text;
}
console.log(begruesse("Ada"));
console.log(begruesse("Linus", "Hi", "Nice to see you."));
function summe(...zahlen: number[]): number {
return zahlen.reduce((s, z) => s + z, 0);
}
console.log(summe(1, 2, 3, 4));Functions are values and have types. You use them to describe callbacks. void means "the return value is not used", never means "never returns":
type Vergleich = (a: number, b: number) => number;
const aufsteigend: Vergleich = (a, b) => a - b; // parameter types are inferred
console.log([3, 1, 2].sort(aufsteigend));
function protokolliere(nachricht: string): void {
console.log("[LOG]", nachricht);
}
function abbruch(grund: string): never {
throw new Error(grund);
}WarningWithout an annotation and without a way to infer it, a parameter becomes implicitly
any – with strict that is an error (noImplicitAny). This is intentional: TypeScript wants you to make a decision.TipFor callbacks (
map, filter, event handlers) TypeScript infers the parameter types from the context – there you usually do not need annotations.