Funtion types

  1. Type of function

    In addition to the types of function parameters, the function itself (return result) also has a type.

    Function return result type TS is also inferred. You should not set the type explicitly if there is no particular reason to do so, and it is better to use TS inference.

    The way to explicitly declare the type of a function is:

    1
    2
    3
    function add(n1: number, n2: number): number {
    return n1 + n2;
    }

    If the result of return does not match the explicitly declared type, TS will report an error.


  2. void, undefined

    A function that does not return any value and is of type void (no explicit declaration required).

    There is a difference between void type and undefined type in TS. The void type indicates that the function does not have a return statement, and the undefined type indicates that the function does not return an actual value when it returns, such as return; (that is, there is a return statement, but it does not return a value).


  3. Type of function variable

    Sometimes we can assign a function to a variable. At this time, the type of the variable is a function.

    1
    2
    3
    4
    5
    6
    function add(n1: number, n2: number): number {
    return n1 + n2;
    }

    let combineValue: (a: number, b:number) => number;
    combineValue = add

    The function variable type is written as an arrow function. Both parameter type and return type must be written.


  4. Type of callback function

    The parameters of a function can also be functions, that is, callback functions. Type writing:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function addAndHandle(n1: number, n2: number, cb: (number) => void) {
    const result = n1 + n2;
    cb(result);
    }
    addAndHandle(10, 20, (result) => {
    console.log(result);
    });
    addAndHandle(10, 20, (result) => {
    console.log(result);
    return result; //No error reported
    });

    It should be noted here that when the callback function type in the main function is void, if the callback function has a return statement and returns a value, no error will be reported. The void type of the callback function means that any value returned by the callback function will not be used by the main function. Therefore it cannot be used in the main function to obtain data using const result2 = cb(result).


  5. Types of arrow functions

    The type of the arrow function can use the function type annotation, that is, (params) => returnType, for example:

    1
    2
    3
    type MyFunc = (a: number, b: number) => number;
    const add: MyFunc = (a, b) => a + b;
    console.log(add(2, 3)); // Output: 5

    How to write the interface of the function:

    1
    2
    3
    4
    5
    interface MyFunc {
    (a: number, b: number): number;
    }
    const add: MyFunc = (a, b) => a + b;
    console.log(add(2, 3)); // Output: 5

Share