Functions

Change Topic
  • Function definition with arguments and a return type - how to pass arguments to a function and express the return type.
  • Function overloading - how to provide multiple different implementations with different sets of arguments
  • Default or Optional Arguments - how to provide defaults or express optionality in arguments
  • Lambda Functions - defining a lambda function
  • Lambda Function Capture - using local in-scope variables inside the lambda function
  • Function Type Parameter (Generics) - how to define a function with one or more types as an argument
  • Function Type Parameter Constraints - how to define a constraint on the type parameter

Select Language

TypeScript Functions


Function Definition with Arguments and Return Type

TypeScript allows specifying argument types and return types explicitly in function definitions.

function add(x: number, y: number): number { return x + y; } const greet = (name: string): string => `Hello, ${name}!`;
  • x: number, y: number: Defines parameter types.
  • : number after () specifies the return type.

Function Overloading

Function overloading processed at runtime

function add(x: number, y: number): number; function add(x: string, y: string): string; function add(x: any, y: any): any { return x + y; } console.log(add(5, 10)); // 15 console.log(add("Hello, ", "World!")); // "Hello, World!"

Function Default Arguments

function doIt(b: number, a = 1) { return b / a; } console.log("DoIt " + doIt(10) + " " + doIt(10, 2));

Lambda Functions

const doIt = (b: number, c: number) => a * b; console.log("DoIt " + doIt(10, 5));

Lambda Function Capture

function createCounter(): () => number { let count = 0; // This variable is captured by the closure return () => { count += 1; return count; }; } const counterA = createCounter(); console.log(counterA()); // 1 console.log(counterA()); // 2 const counterB = createCounter(); console.log(counterB()); // 1 (separate closure) console.log(counterA()); // 3 (original closure still intact)
function makeMultiplier(factor: number): (input: number) => number { // factor is captured by the inner function return (input: number) => input * factor; } const double = makeMultiplier(2); const triple = makeMultiplier(3); console.log(double(5)); // 10 console.log(triple(5)); // 15

Function Generics

function identity<T>(value: T): T { return value; } console.log(identity<number>(42)); // 42 console.log(identity<string>("Hello")); // "Hello"

Function Generics Constraint

And with a constraint:

function getLength<T extends { length: number }>(arg: T): number { return arg.length; } console.log(getLength("Hello")); // 5 console.log(getLength([1, 2, 3])); // 3