Skip to main content

Functions

January 30, 2024Less than 1 minute

Functions

  • The TypeScript type system pays a lot of love to functions
  • Functions in TS can also be typed (parameters and return type)
function add(a: number, b: number): number {
    return a + b;
}

const multiply = (a: number, b: number): number => a * b;

Parameter annotations

  • You can annotate function parameters in the same way as you annotate variables:
function log(message: string) { }

function foo(sampleParameter: { bar: number }) { }

Return type annotation

  • You can annotate the return type after the function parameter list with the same style as you use for a variable
interface Foo {
    foo: string;
}

// Return type annotated as `: Foo`
function foo(sample: Foo): Foo {
    return sample;
}

// Return string
function upperCase(message: string): string {
    return message.toUpperCase();
}

// Don't return anything: void
function warn(message: string): void {}

Optional parameters

  • You can mark a parameter as optional with the ? symbol
function foo(bar: number, bas?: string): void {
    // ..
}

foo(123);
foo(123, 'hello');

Default values

  • You can set a default value for a parameter with the = symbol
function foo(bar: number, bas: string = 'hello') {
    console.log(bar, bas);
}

foo(123);           // 123, hello
foo(123, 'world');  // 123, world

Overloading

  • TypeScript allows you to declare function overloads
  • This is useful for documentation and type safety
// Overloads
function padding(all: number);
function padding(topAndBottom: number, leftAndRight: number);
function padding(top: number, right: number, bottom: number, left: number);
// Actual implementation that is a true representation of all the cases the function body needs to handle
function padding(a: number, b?: number, c?: number, d?: number) {
    if (b === undefined && c === undefined && d === undefined) {
        b = c = d = a;
    }
    else if (c === undefined && d === undefined) {
        c = a;
        d = b;
    }
    return {
        top: a,
        right: b,
        bottom: c,
        left: d
    };
}