TypeScript Functions

up:: Typescript

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

You can annotate the function parameters and return type. In the example above, I used an interface but inline annotations also work.

If a function does not return anything, it’s return type is void.

function foo(bar: number, bas?: string): void {
    // ..
}
 
foo(123);
foo(123, 'hello');

Function overloading

From Functions - TypeScript Deep Dive

Function overloading means that a function does different things based on how many parameters are provided. For example, padding(1), padding(1, 1) and padding(1,1,1,1) could all do different things. TypeScript supports this kind of declaration:

// 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
    };
}
padding(1); // Okay: all
padding(1,1); // Okay: topAndBottom, leftAndRight
padding(1,1,1,1); // Okay: top, right, bottom, left
 
padding(1,1,1); // Error: Not a part of the available overloads