Functions in TypeScript

Functions are central in TypeScript. We’ll learn about functions with a few different examples.

// Here's a function that takes two numbers and returns
// their sum as a number.
function plus(a: number, b: number): number {
    // TypeScript doesn't require explicit returns, but it's
    // good practice to include them for clarity.
    return a + b;
}

// In TypeScript, you can use optional parameters or default
// parameters instead of function overloading for multiple
// consecutive parameters of the same type.
function plusPlus(a: number, b: number, c: number = 0): number {
    return a + b + c;
}

// The main function in TypeScript is typically the entry
// point of the program, but it's not required.
function main() {
    // Call a function just as you'd expect, with
    // name(args).
    let res = plus(1, 2);
    console.log("1+2 =", res);

    res = plusPlus(1, 2, 3);
    console.log("1+2+3 =", res);
}

// Call the main function to run the program
main();

To run the program, save it as functions.ts and use ts-node (assuming you have it installed):

$ ts-node functions.ts
1+2 = 3
1+2+3 = 6

There are several other features to TypeScript functions. One is optional and default parameters, which we’ve seen in the plusPlus function. Another is rest parameters, which allow a function to accept any number of arguments as an array.