TypeScript - Function Types



Function types in TypeScript allows us to define the types for the functions.

Function type describes the shape of the function, including the parameters and return values.

Function types consist of the following −

  • Type of function parameters

  • Return type of the function

Typing a Function

Typing a function refers to specifying types for the its parameters and return values. Similar to how we add types to variables, we can also add type annotations to function parameters and return values as we define for the variables.

Let's see how typing a function works with a simple function,

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

In the first example, we added types for the parameters x and y and the return type of the function. TypeScript can infer the return type using the types of the parameters. This means that optionally we can leave the return type out.

In the second example, we assigned a function to the variable addNums. While we didn't explicitly define a type of addNums, TypeScript can infer its type.

Let’s now check how TypeScript compiler infers the type of a variable assigned with a function.

TypeScript infers the type of the variable

In the below example, we have assigned a function to variable add −

let add = function (a: number, b: number): number {
   return a + b;
}

The TypeScript compiler infers the type of the add variable as −

(a: number, b: number) => number

Look at the following screenshot, the typescript editor infers the type of the add variable.

Function Types Inference

Here, "(a: number, b: number) => number" is basically a function type expression.

The function type expression is a convenient way to declare a variable that hold a function.

TypeScript Function Type Expression

The function types in TypeScript can be defined using function type expressions. Function type expression is syntactically similar to the arrow function.

Syntax

Within function type expression, we specify the types of parameters and the return type. The syntax is as follows −

(para1: type1, para2: type2, ...) => returnType

Where,

  • (para1: type1, para2: type2, ...): This defines the function’s parameters and their types. We can add multiple parameters separated by commas.

  • =>: The fat arrow separates the parameters list from the return type.

  • returnType: This is the type of the return value of function.

Example to demonstrate the function type in TypeScript −

(name: string) => void

This function type is described as a function with one parameter, named name, of string type, that has no return value (indicated by void).

(a: number, b: number) => number

In the above function type, it takes two parameters named a and b of number types and return a value of type number.

Example

Let's declare a variable named addFun of function type using function type expression −

let addFun: (x: number, y: number) => number = function (x:number, y: number): number {
   return x + y
}
console.log(addFun(2, 3));

In the above example, we add a function to addFun that takes two number as parameters and returns their sum. The type annotation "(x: number, y: number) => number" clarifies this behavior.

On compiling this TypeScript code, it will generate the following JavaScript code.

let addFun = function (x, y) {
    return x + y;
};
console.log(addFun(2, 3));

The output of the above example code is as follows −

5

Example

Let's take another example −

const greet: (name: string) => string = (name) => {
  return `Hello, ${name}!`;
};
console.log(greet("Shahid"));

In the below example, we define a constant greet of type (name: string) => string. This function takes a string as a parameter and returns a string.

The above TypeScript code will compile to the following JavaScript code.

const greet = (name) => {
    return `Hello, ${name}!`;
};
console.log(greet("Shahid"));

The output of the above example code is as follows −

Hello, Shahid!

Declaring Function Type Variable

In TypeScript, we can declare a variable with a specific function type using function type expression.

Let’s declare a variable of function type −

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

This declares a variable add of function type. The function takes two numbers as argument and returns a number.

Example

In the Example below, we declare the variable greet of the function type using function expression. And then assign the variable with a function that takes a parameter of type string and returns a string.

let greet: (name: string) => string;
greet = (name) => {
  return `Hello, ${name}!`;
};
console.log(greet('John'));

On compiling, it will generate the following JavaScript code −

let greet;
greet = (name) => {
    return `Hello, ${name}!`;
};
console.log(greet('John'));

The output is as follows −

Hello, John!

Specifying Function Parameters as Functions

We can specify a parameter of type function. In the below example, the parameter fn is specified as of a function type. It accepts a parameter of type string and it does not return any value.

The function greet accepts a parameter named fn, of type function.

function greet (fn: (s: string) => void) {
   fn ("Welcome to Tutorials Point!")
}
function print (str: string) {
   console.log(str);
}
greet(print);

On compiling, it will generate the following JavaScript code.

function greet(fn) {
    fn("Welcome to Tutorials Point!");
}
function print(str) {
    console.log(str);
}
greet(print);

The output of the above example code is as follows −

Welcome to Tutorials Point!

Using Type Aliases to Function Types

We can create a type alias to represent a specific function type and use it within out code −

type funcType = (s: string) => void;
function greet (fn: funcType) {
   fn ("Welcome to Tutorials Point!")
}
function print (str: string) {
   console.log(str);
}
greet(print);

Here we define a type alias functType for the function type "(s: string) => void". Further we use funcType as type of parameter in the definition of function greet.

On compiling, it will generate the following JavaScript code.

function greet(fn) {
    fn("Welcome to Tutorials Point!");
}
function print(str) {
    console.log(str);
}
greet(print);

The output of the above example is as follows −

Welcome to Tutorials Point!
Advertisements