So far, we have seen how to add type annotations to variables, and have also seen how this syntax is easily extended to function parameters. There are, however, a few more typing rules that TypeScript uses when it comes to functions.

Function return types

Using the very simple "syntactic sugar" TypeScript syntax, we can also define the type of a variable that a function should return. In other words, when we call a function, and it returns a value, what type should the value be treated as ?

Consider the following TypeScript code:

    function addNumbers(a: number, b: number) : string { 
      return a + b; 
    var addResult = addNumbers(2,3); 
    console.log(`addNumbers returned : ${addResult}`);

Here, we have added a :number type to both of the parameters ...

Get Mastering TypeScript - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.