TypeScript / TypeScript Basics

Understanding Type Annotations and Type Inference

Learn how to use type annotations and understand type inference in TypeScript. This tutorial will guide you through the process of declaring variables with explicit types and how …

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of TypeScript, including type annotations, variables, and basic syntax.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help