Skip to main content

Type Annotations

Type Annotations are a fundamental part of TypeScript. They provide a way to enforce certain types on the variables, so that type related errors can be caught at compile time, rather than runtime. This feature greatly improves the quality of your code and makes it more understandable.

What are Type Annotations in TypeScript?

Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. In other words, type annotations are a way of telling TypeScript what type a variable should be.

Here is a simple example on how to specify a type annotation for a variable:

let name: string;
name = "John Doe";

In this example, we are telling TypeScript that the name variable will be a string. If you try to assign a non-string value to this variable, TypeScript will flag an error.

Basic Types in TypeScript

TypeScript supports the same types as JavaScript, with a convenient enumeration type thrown in to help things along.

Here are the basic types in TypeScript:

  • boolean: It represents a logical value.
let isDone: boolean = false;
  • number: It represents a number type.
let decimal: number = 6;
  • string: It represents a string type.
let color: string = "blue";
  • array: It represents an array type.
let list: number[] = [1, 2, 3];
  • tuple: It represents a tuple type, which allows you to express an array where the type of a fixed number of elements is known but need not be the same.
let x: [string, number];
x = ["hello", 10];
  • enum: A way of giving more friendly names to sets of numeric values.
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
  • any: We may need to describe the type of variables that we do not know when we are writing an application.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
  • void: It is a little like the opposite of any, the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value.
function warnUser(): void {
alert("This is my warning message");
}

Why Use Type Annotations?

Type annotations are optional in TypeScript because of type inference. However, they are very useful for catching type-related errors at compile time. This can prevent many runtime errors, making your code safer.

In addition, type annotations can make your code more readable and self-documenting. By looking at the type annotation, one can quickly understand what type of values a function expects or what type of value a variable represents.

In conclusion, type annotations in TypeScript are a powerful feature that helps to keep your code error-free, readable, and easy to understand. It's a good practice to use type annotations, especially in large codebases, for better maintainability and reliability of your code.