Advanced TypeScript typing

Typing

Functions

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

With object as argument and/or return value.

function add(values: { x: number, y: number }): { result: number } {
    return {result: x + y };
}

Arrow functions

const add: (x: number, y: number) => number = (x: number, y: number) => {
    return x + y;
}

TypeScript compiler can figure out the type even if you only have types on one side of the equation:

const add: (x: number, y: number) => number = (x, y) => {
    return x + y;
}

Classes

class Machine {
    x: number;
    y: number;

    constructor(x: number = 0, y: number = 0) {
        this.x = x;
        this.y = y;
    }

    add(): numer {
        return this.x + this.y
    }
}

class SuperMachine extends Machine {
    multiplication(): number {
        return this.x * this.y
    }
}

let calculator: SuperMachine = new SuperMachine(1, 2);

React class component

class Machine extends React.Component<{x: number; y: number}> {
    const result = this.props.x + this.props.y;
    render() {
        return <span>{result}</span>
    }
}

React functional component

const Machine: React.FC<{x: number; y: number}> = ({x, y}) => {
    const result = x + y;
    return <span>{result}</span>
}