Last updated: 2026-05-05

Functions and typing in TypeScript

Variables are not the only elements that can be restricted and protected with type safety. Functions can also be restricted by type safety to ensure the right data types are passed as arguments and returned when the function is executed.

This happens by dictating the function parameters and its return results.

FeatureDescriptionExample
Parameter TypesDefine the type for function parameters.function greet(name: string) {}
Return Type AnnotationSpecify the type of the returned value.function add(a: number, b: number): number { return a + b; }
void Return TypeUsed when a function does not return a value — for example, functions that log to the console or update the DOM.function logMessage(msg: string): void { console.log(msg); }
Optional Parameters (?)Parameters that are not required when calling the function.function welcome(name: string, age?: number) {}
Default ParametersAssigns a default value if no argument is provided.function format(price: number, currency: string = "USD") {}
Function ExpressionsAssign functions to variables.const multiply = function (x: number, y: number): number { return x * y; };
Arrow FunctionsA shorter syntax for functions.const divide = (a: number, b: number): number => a / b;
Function Type AliasesDefine a function structure as a type.type MathOp = (x: number, y: number) => number;