Skip to content

Arrays, Tuples, Enums, and Classes

let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["A", "B", "C"];

Both syntaxes are valid.


let matrix: number[][] = [
[1, 2],
[3, 4],
];

Tuples are fixed-length arrays with fixed order of types.

let user: [string, number] = ["Sahil", 22];

Common use cases:

  • React hooks return values
  • helper functions returning multiple values

enum Status {
Pending,
Success,
Failed,
}

Enums generate JavaScript output at runtime.

Modern alternative:

type Status = "pending" | "success" | "failed";

class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}

class Account {
public owner: string;
private balance: number;
protected accountId: string;
constructor(owner: string, balance: number, accountId: string) {
this.owner = owner;
this.balance = balance;
this.accountId = accountId;
}
}

public

Accessible from anywhere.

private

Accessible only inside the same class.

protected

Accessible in class and subclasses.


class MathUtil {
static PI = 3.14159;
}
const value = MathUtil.PI;

Static members belong to the class, not instances.


abstract class Animal {
abstract makeSound(): void;
}
class Dog extends Animal {
override makeSound(): void {
console.log("Woof");
}
}
graph TD A[Abstract Class Animal] --> B[Dog] A --> C[Cat] B --> D[Override makeSound] C --> E[Override makeSound]