Skip to content

TypeScript Functions

Functions are the fundamental building blocks of any application, used to perform specific tasks. In TypeScript, we can add types to function parameters and return values, making functions more robust and easier to understand.

Defining Functions

You can create functions using function declarations or function expressions.

Function Declaration

typescript
// Named function
function add(x: number, y: number): number {
    return x + y;
}

Function Expression

typescript
// Anonymous function
const subtract = function(x: number, y: number): number {
    return x - y;
};

Function Types

We can define a function type for a variable, so it can only hold a function that matches that type.

typescript
let myAdd: (baseValue: number, increment: number) => number;

myAdd = function(x: number, y: number): number {
    return x + y;
};

// myAdd = function(a: string, b: string): string { return a + b; }; // Error

Parameter Types

1. Type Annotation and Type Inference

As shown in the examples above, you can add type annotations to function parameters. The return value type can also be annotated. If you omit the return type annotation, TypeScript will try to infer it based on the return statements.

typescript
function multiply(x: number, y: number) { // Return type is inferred as number
    return x * y;
}

2. Optional Parameters

In TypeScript, every function parameter is considered required. However, you can mark a parameter as optional by using ? after the parameter name.

Optional parameters must come after required parameters.

typescript
function buildName(firstName: string, lastName?: string): string {
    if (lastName) {
        return `${firstName} ${lastName}`;
    }
    return firstName;
}

let result1 = buildName("Bob"); // OK
let result2 = buildName("Bob", "Adams"); // OK
// let result3 = buildName("Bob", "Adams", "Sr."); // Error, too many parameters

3. Default Parameters

You can set a default value for a parameter. When the user doesn't provide that parameter or provides undefined, the parameter will use the default value.

typescript
function calculatePay(rate: number, hours: number = 40): number {
    return rate * hours;
}

let pay1 = calculatePay(25); // 25 * 40 = 1000
let pay2 = calculatePay(25, 30); // 25 * 30 = 750

Unlike optional parameters, parameters with default values don't have to come after required parameters.

4. Rest Parameters

If you need to handle multiple parameters as a group, or you don't know how many parameters a function will ultimately receive, you can use rest parameters. They are collected into an array.

typescript
function sum(...numbers: number[]): number {
    let total = 0;
    for (const num of numbers) {
        total += num;
    }
    return total;
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100

Arrow Functions

Arrow functions are a more concise function syntax introduced in ES6. They also solve the issue of how the this keyword behaves in traditional functions.

Syntax

typescript
const numbers = [1, 2, 3, 4, 5];

// Traditional function
const squared1 = numbers.map(function(n) {
    return n * n;
});

// Arrow function
const squared2 = numbers.map(n => n * n);

Behavior of this

In arrow functions, the value of this is determined by the context where the function is created, not where it's called. This is very useful when handling event handlers or callback functions.

typescript
class MyClass {
    value: number = 10;

    // Using arrow function as method
    start = () => {
        // 'this' here refers to the instance of MyClass
        setInterval(() => {
            console.log(this.value);
        }, 1000);
    }
}

let myInstance = new MyClass();
myInstance.start();

If start were a regular function, this in the setInterval callback would be window (in browsers) or undefined (in strict mode), causing this.value to error.

Content is for learning and research only.