Menu
Courses / TypeScript Basics / functions

functions

03 / 10 Part of TypeScript Basics

Typing Function Parameters and Return Values


TypeScript lets you specify the type of every parameter, as well as what type the function returns.


function add(a: number, b: number): number {
    return a + b;
}

add(5, 3);     // 8
add(5, "3");   // Error: Argument of type 'string' is not assignable to parameter of type 'number'


Optional Parameters


Add a ? after a parameter name to make it optional. Optional parameters must come after required ones.


function greet(name: string, title?: string): string {
    if (title) {
        return `Hello, ${title} ${name}!`;
    }
    return `Hello, ${name}!`;
}

greet("Smith", "Dr.");  // Hello, Dr. Smith!
greet("Alice");         // Hello, Alice!


Default Parameters


You can give a parameter a default value, used whenever the caller doesn't provide one.


function multiply(a: number, b: number = 2): number {
    return a * b;
}

multiply(5);     // 10 (b defaults to 2)
multiply(5, 3);  // 15


Rest Parameters


Use ... to accept an unlimited number of arguments as an array.


function sumAll(...numbers: number[]): number {
    return numbers.reduce((total, n) => total + n, 0);
}

sumAll(1, 2, 3);        // 6
sumAll(10, 20, 30, 40); // 100


Arrow Functions


A more compact function syntax, very common in modern TypeScript and JavaScript.


const add = (a: number, b: number): number => a + b;

const greet = (name: string): void => {
    console.log(`Hi, ${name}`);
};


Function Types


You can describe the "shape" of a function as its own type — useful for parameters or variables that hold a function.


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

mathOperation = (a, b) => a + b;
mathOperation = (a, b) => a * b;


Void vs Undefined Return


function logAction(action: string): void {
    console.log(`Performing: ${action}`);
    // no return statement needed
}


Function Overloads


TypeScript allows you to define multiple call signatures for the same function name, useful when a function behaves differently depending on the input type.


function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
    return a + b;
}

combine("Hello, ", "World"); // "Hello, World"
combine(5, 10);              // 15


Quick Reference



   
   
       
       
       
       
   
FeatureSyntax Example
Optional parameterfunction f(x?: number)
Default parameterfunction f(x: number = 5)
Rest parameterfunction f(...args: number[])
Arrow functionconst f = (x: number): number => x * 2



    Coming up next: Interfaces and type aliases — how to describe the shape of objects in TypeScript.