TypeScript Function Types: Complete Guide To Become a Pro

Robin
Updated on February 26, 2023

TypeScript function type allows you to define the structure of a function which can help prevent errors and improve code clarity. By specifying a type for a function, you can ensure the type and number of parameters it will accept and what type of value it will return.

In this blog post, we'll take an in-depth look at TypeScript Function Type and explore its syntax. You will learn everything from basic function types to more advanced techniques like optional parameters and types for callback functions.

The Syntax for Function Types in TypeScript

By defining a Function Type, you can use it to ensure that any function you assign to it has the correct format. This can help catch errors early in the development process and make code more self-documenting.

To define a Function Type in TypeScript, you start by using the "=>" notation, which separates the parameter types and the return type. The parameter types are listed inside parentheses, separated by commas, and you will add the return type after the "=>" notation.

          (parameter: type, parameter:type,...) => return type
        

You can declare as many parameters as you need for your function with their types inside parentheses. Let's see an example.

          let myFunc: (num1: number, num2: number) => number;
        

Here I am declaring a variable called myFunc with its type. I am using a function type so that this variable can only hold a function of a specific format.

This function type has 2 parameters. Both parameters will be numbers and it will also return a number. Now whenever you will try to put a value in this variable, TypeScript will check if the value matches the declared function type.

          type AddFunc = (num1: number, num2: number) => number
        

If you want to use a function type in multiple places, you can define it using the type keyword. Now you can use this AddFunc type for multiple variables.

Also Read: Mastering Type Casting in TypeScript: A Complete Guide

Creating TypeScript Function Types

You have seen the basic syntax of function type in TypeScript. Now let's see how you can assign it to a real function. I defined an AddFunc type in the previous section, I will use this type with my function.

          type AddFunc = (num1: number, num2: number) => number

const myFunction: AddFunc = (a: number, b: number): number => {
    return a + b
}

const result = myFunction(38, 12)

console.log(result)
// 50
        

I am assigning my AddFunc type to the myFunction variable. TypeScript will only allow me to put a function in this variable that takes 2 number parameters and also returns a number.

If you try to store any other value in this variable, TypeScript will throw an error. In this way, you can catch unexpected errors very easily in the development process. As TypeScript already knows about the format of this function, it will give you suggestions.

Adding Types For Callback Functions

When a function is passed as an argument to another function and gets executed inside that other function then it is called a callback function.

While creating a type for a function, you can also add a type for the callback function.

          type Callback = (result: number) => void
type AddFunc = (num1: number, num2: number, cb: Callback) => void

const myFunction: AddFunc = (a: number, b: number, cb) => {
    const sum = a + b

    cb(sum)
}

myFunction(38, 12, (result) => {
    console.log(result)
    // 50
})
        

I have added two function types AddFunc (for the main function) and Callback (for the callback function) in this example. The AddFunc type has 3 parameters: the first 2 parameters are numbers and the last parameter is of type "Callback".

By using the AddFunc type with the myFunction function, you can ensure that your function has the correct signature. There is another advantage of applying type to your callback function.

The Callback type has one parameter which is of type number. That's why if you call this myFunction() function with those parameters, TypeScript will know about the type of your callback function's argument. In this case, the type of result is a number.

Advanced Techniques For Function Types

We can define function parameters in different ways. That's why you need to know some advanced techniques for your function types in TypeScript. These are the things you can do with your function types:

  • Setting types for optional parameters.
  • Declaring types for rest parameters.

Optional Parameters:

You can specify whether a parameter is optional or not by adding a "?" after the parameter name.

          type AddFunc = (num1: number, num2?: number) => number

const myFunction: AddFunc = (a: number, b?: number): number => {
    if (b) {
        return a + b
    }

    return a
}

const result = myFunction(38)

console.log(result)
// 38
        

Here I am setting the second parameter in this AddFunc type as optional by adding a question mark (?) at the end of this parameter name.

Rest Parameters:

Rest parameters allow you to pass any number of arguments to a function. You can declare such a parameter by an ellipsis (...) before the parameter name.

          type AddFunc = (...numbers: number[]) => number

const myFunction: AddFunc = (...values: number[]): number => {
    let sum = 0

    values.forEach((value) => {
        sum += value
    })

    return sum
}

const result = myFunction(38, 12, 45, 23)

console.log(result)
// 118
        

In my AddFunc function type, I am using a rest parameter as a number array. It's a function type that takes any number of arguments of type number using the rest parameter syntax ...numbers, and returns a value of type number.

Also Read: TypeScript Function Overloading: Learn Best Ways to Use It

Conclusion

TypeScript Function Types provide static typing for functions, which will help you to catch errors and provide code suggestions in the development process.

You will use the function type to define the structure of a function with the types of its parameters and return values. It will give you a better experience because TypeScript will be able to help you more while writing code.

In this guide, we have discussed everything about function type in TypeScript from basics to advanced features including its syntax, and how to create and apply it to our functions.

Related Posts