Understanding Type Annotations and Type Inference

Tutorial 2 of 5

1. Introduction

This tutorial aims to provide an understanding of type annotations and type inference in TypeScript. TypeScript, a statically typed superset of JavaScript, enforces type checking at compile time, leading to the prevention of potential runtime errors. Two fundamental aspects of TypeScript's static type checking are Type Annotations and Type Inference.

By the end of this tutorial, you will learn:

  • How to declare variables with explicit types (Type Annotations)
  • How TypeScript infers types when not explicitly declared (Type Inference)

Prerequisites: Basic knowledge of JavaScript and an understanding of TypeScript is helpful, though not strictly necessary.

2. Step-by-Step Guide

Type Annotations

Type Annotations in TypeScript are a way of explicitly specifying the type of a variable at the time of declaration.

let message: string;
message = 'Hello World';

In the above code message is explicitly declared as a string. Trying to assign a non-string value to message will throw a compile-time error.

Type Inference

TypeScript can often infer types without explicit annotations based on how variables are initialized and used. This is known as Type Inference.

let message = 'Hello World';

In the above code, TypeScript infers message to be a string because it's initialized with a string.

Best practice: Let TypeScript infer types whenever possible. Use type annotations when the type cannot be inferred.

3. Code Examples

Example 1: Explicit Type Annotation

let age: number;
age = 25; // This is fine
age = 'Twenty Five'; // This will throw an error as age is of type number

Example 2: Type Inference

let isAdult = true; 
// TypeScript infers isAdult to be of type boolean since it is initialized with a boolean value
isAdult = 'yes'; // This will throw an error

Example 3: Function Parameter Type Annotation

function greet(name: string) {
  console.log(`Hello, ${name}`);
}
greet('Alice'); // This is fine
greet(123); // This will throw an error as the argument should be a string

4. Summary

In this tutorial, you learned about:

  • Type Annotations in TypeScript and how to use them
  • Type Inference in TypeScript and how it works

Next steps: Explore more about TypeScript's static types like tuples, enums, and any. Also, understand the concept of Interfaces in TypeScript.

Additional resources:

5. Practice Exercises

  1. Declare a variable year with type number and assign it your birth year.
  2. Declare a variable name and assign it your name. Let TypeScript infer the type.
  3. Write a function add that takes two parameters of type number and returns their sum.

Solutions:

1.

let year: number;
year = 1990;

2.

let name = 'John';

3.

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

Continue practicing by creating more variables and functions with explicit type annotations and letting TypeScript infer types where possible.