Functions
Functions
Section titled βFunctionsβWhat it means
Section titled βWhat it meansβTypeScript lets you annotate a functionβs parameter types and return type, so the compiler can catch mismatched arguments or incorrect usage of the return value before the code ever runs. Function types can also be written standalone (e.g. as a type alias) to describe callback shapes.
Examples
Section titled βExamplesβfunction add(a: number, b: number): number { return a + b;}
add(2, 3); // 5// add(2, "3"); // Error: argument of type 'string' not assignable to 'number'
// Arrow function with typesconst multiply = (a: number, b: number): number => a * b;
// A standalone function type, useful for callbackstype BinaryOp = (a: number, b: number) => number;
function calculate(a: number, b: number, op: BinaryOp): number { return op(a, b);}calculate(4, 5, add); // 9calculate(4, 5, multiply); // 20Common mistake
Section titled βCommon mistakeβRelying on TypeScript to infer a functionβs return type and being surprised when a refactor silently changes it β without an explicit return type annotation, changing the bodyβs logic can change the inferred return type without any error, propagating the mismatch to every caller.
// No explicit return type -- TypeScript infers `number`function getDiscount(price: number) { return price * 0.1;}
// Later, someone "improves" it...function getDiscount(price: number) { return `${price * 0.1}`; // oops, now returns a string -- no error here!}// Every caller expecting a number now silently gets a string, discovered only downstream
// Fix: annotate the return type explicitly, so this change WOULD error immediatelyfunction getDiscount(price: number): number { return `${price * 0.1}`; // Error: string not assignable to number}Quick practice
Section titled βQuick practiceβ-
What does adding
: numberafter a functionβs parameter list specify?Answer
The function's return type β TypeScript checks that everyreturnstatement matches it. -
Why might you write an explicit return type even when TypeScript can infer it?
Answer
It acts as a safety net β if a future code change accidentally alters what the function returns, the explicit annotation causes an immediate compile error instead of silently propagating the wrong type to callers. -
How do you write a standalone type for a function that takes two numbers and returns a number?
Answer
type BinaryOp = (a: number, b: number) => number;