Codectionary / Developer documentation / TypeScript

Typing Functions

Function parameters and return types can be explicitly typed for safety and clarity. Optional parameters (marked with ?) must come after required ones, and default parameter values let TypeScript infer their type automatically. Function type expressions let you type a variable that holds a function, describing exactly what parameters and return type it must have.

Syntax

function name(param: type): returnType { }

Examples

Parameters and Return Types

The fundamentals of typing a function signature.

function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

function logResult(value: number, label?: string): void {
  // label is optional - type is "string | undefined"
  console.log(label ? `${label}: ${value}` : value);
}

greet("Alice");           // uses default greeting
greet("Bob", "Hi");        // overrides it

Typing a Function as a Value

Describing the shape of a function stored in a variable or passed as an argument.

let mathOperation: (a: number, b: number) => number;

mathOperation = (a, b) => a + b; // parameter types are inferred from the variable's type

function applyOperation(a: number, b: number, operation: (x: number, y: number) => number): number {
  return operation(a, b);
}

console.log(applyOperation(5, 3, (x, y) => x * y)); // 15

Best practices

  • Always type function parameters explicitly - TypeScript cannot infer them the way it infers return types
  • Place optional parameters after all required parameters in a function signature - required parameters cannot follow optional ones
  • Let TypeScript infer the return type in most cases rather than annotating it explicitly, unless the function is part of a public API where an explicit contract is valuable
  • Use a function type expression when a variable or parameter itself needs to hold a function, describing its expected signature precisely

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation