DEV Community

Rakan
Rakan

Posted on

TypeScript: Type Annotations and Type Inference

As I go through the typescript course, here are some things I have learned. In TypeScript, there are two important concepts: Type annotations and Type inference.

Type Annotations: We, as developers, use type annotations to tell TypeScript the type of value a variable will have. For example:

let apples: number = 5;
Enter fullscreen mode Exit fullscreen mode

Here, we're saying that apples will always be a number. If we try to assign a string, TypeScript will show an error.

Type Inference: TypeScript tries to figure out the type of a variable by itself. For example:

let apples = 5;
Enter fullscreen mode Exit fullscreen mode

When we declare and initialize a variable in one line, TypeScript guesses its type. In this case, it's a number. If we try to assign a string, TypeScript will show an error.


When to use each one?

Type Inference: Use it whenever possible. Let TypeScript do the work of figuring out types for you.

Type Annotations:

  • When declaring a variable and initializing it in separate lines:
let apples; // should be let apples: number;
Enter fullscreen mode Exit fullscreen mode
  • When a function needs to clarify the type it returns:
const numberToString = (num: number): string => {
    return num.toString();
}
Enter fullscreen mode Exit fullscreen mode
  • When a variable's type can't be inferred(guessed by TypeScript):

When Typescript can't figure out the intended type (a scenario where a variable could potentially have multiple types), we need to use type annotations. For example:

let words = ['red', 'green', 'blue'];
let foundWord = false;

for (let i = 0; i < words.length; i++) {
    if (words[i] === 'green') {
        foundWord = words[i];
    }
}
Enter fullscreen mode Exit fullscreen mode

to fix this, we need to add type annotations to foundWord variable:

let words = ['red', 'green', 'blue'];
let foundWord: boolean | string = false;
Enter fullscreen mode Exit fullscreen mode

Resources:

Top comments (0)