TypeScript Types

Page 1 of 4

Any

A flexible type that opts out of type checking.

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type checking. When a value is of type any, you can access any properties of it, call it like a function, or assign it to a variable of any other type.

Example of usage

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

Notes

  • Using any effectively disables all compile-time type checking for the variable.
  • It should be used sparingly, as it undermines the benefits of TypeScript. The unknown type is often a safer alternative.

Array

Represents a collection of values of the same type.

Arrays in TypeScript can be written in two ways. The first, and most common, uses square brackets [] to denote the type of elements in the array. The second way uses a generic Array<elemType> syntax.

Example of usage

let list: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob", "Charlie"];

names.push("David");

Notes

  • Arrays are zero-indexed, meaning the first element is at index 0.
  • TypeScript provides strong typing for array elements, preventing you from adding elements of the wrong type.

Boolean

Represents one of two values: true or false.

The boolean type is a fundamental primitive type in TypeScript. It can only have two values: true or false. It’s commonly used for controlling program flow, such as in if statements and loops.

Example of usage

let isDone: boolean = false;
let isLoggedIn: boolean = true;

if (isLoggedIn) {
  console.log("Welcome back!");
}

Notes

  • Avoid using the Boolean object wrapper (new Boolean(value)), as it behaves differently from the primitive boolean type.