Function types

We already know that it is possible to explicitly declare the type of an element in our application by using optional type annotations:

function greetNamed(name: string): string { 
    return `Hi! ${name}`; 
} 

In the preceding function, we have specified the type of the parameter name (string) and its return type (string). Sometimes, we will need to not just specify the types of the function elements, but the function itself. Let's look at an example:

let greetUnnamed: (name: string) => string; 
 
greetUnnamed = function(name: string): string { 
    return `Hi! ${name}`; 
}; 

In the preceding example, we have declared the greetUnnamed variable and its type. The greetUnnamed type is a function type that takes a string variable called name ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.