Affiliate link

TypeScript - Data types

In TypeScript, types are used to define the shape and behavior of data. Types help to catch errors at compile-time and make your code more maintainable and scalable. In this chapter, we will explore the basic types in TypeScript and learn how to use them.

Boolean

The Boolean type in TypeScript represents a boolean value, either true or false.

let isDone: boolean = false;

Number

The Number type in TypeScript represents both integer and floating-point numbers.

let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

String

The String type in TypeScript represents a sequence of characters.

let color: string = "blue";
color = 'red';

let fullName: string = "John Doe";
let age: number = 30;
let sentence: string = `My name is ${fullName}. I am ${age} years old.`;

Array

The Array type in TypeScript represents a collection of values of the same type.

let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

Tuple

The Tuple type in TypeScript represents an array with a fixed number of elements, each with a different type.

let x: [string, number];
x = ["hello", 10]; // OK
x = [10, "hello"]; // Error

Enum

The Enum type in TypeScript represents a set of named constants.

enum Color {Red, Green, Blue};
let c: Color = Color.Green;

Any

The Any type in TypeScript represents any type. This type is used when you don't know the type of a value at compile-time.

enum Color {Red, Green, Blue};
let c: Color = Color.Green;

Void

The Void type in TypeScript represents the absence of any type. This type is often used as the return type of a function that doesn't return a value.

function logMessage(): void {
    console.log("Hello, world!");
}

Null and Undefined

The Null and Undefined types in TypeScript represent the absence of a value.

let u: undefined = undefined;
let n: null = null;
Affiliate link
Affiliate link
Advertisment
Get Surfshark VPN
rocket.net