2.3 Function types

We will now learn how to declare the type of a function using optional type annotations.

Getting Ready

All you need to be able to use function types is an installation of TypeScript 2.0 or higher.

How to do it…

If we have a function without type annotations like the following:

const saySomething = function(something) {
  return `says: ${something}`;
}

const text = saySomething("test"); 
console.log(text); // "says: test"

We can add annotations to the function as follows:

const saySomething = function(something: string): string {
  return `says: ${something}`;
}

const text = saySomething("test"); 
console.log(text); // "says: test"

We can go even further and declare the type of the entire function as opposed to only declaring the types of its arguments and return:

const saySomething: (something: <b>string) => string</b> = function(something) {
  return `says: ${something}`;
}

const text = saySomething("test"); 
console.log(text); // "says: test"

How it works…

In the preceding example, we have declared a variable named saySomething and we used an optional type annotation to indicate that this variable will contain a function. The optional type annotation allowed us to specify all the details of the function’s signature:

(something: string) => string

If we try to assign a function with a different signature to the saySomething function, we will get a compilation error:

const saySomething: (something: string) => string = function(something) {
  return `says: ${something}`;
}

saySomething = function(something, somethingElse) {
  return `says: ${something}`;
}

const text = saySomething("test"); 
console.log(text); // "says: test"

The error is caused because the new value of the saySomething variable has a different signature:

(something: string, somethingElse: any) => string

There’s more…

You can also separate the declaration of the type of a function from the declaration of the function itself as follows:

let saySomething: (something: string) => string; 

saySomething = function(something) {
  return `says: ${something}`;
}

const text = saySomething("test"); 
console.log(text); // "says: test"

This is particularly useful when you need to declare the type of a callback function:

Function example(cb: (something: string) => string) {
  // ...
}

Source Code

Function types

See also

Please refer to the recipe about Arrow functions the polymorphic this operator to learn more about arrow functions.


Shiv Kushwaha

Author/Programmer