public
Can be accessed from anywhere, no restrictions.
Arrays, tuples, enums, and classes are basic building blocks in TypeScript. They help you organize and structure your data in a clean way. In this section, we will learn how to work with typed arrays, create tuples for collections that have a fixed length, define enums for a set of named values, and use classes with access modifiers, static members, and abstract classes. By the end of this section, you will understand how to use these features to write clean and easy-to-maintain TypeScript code.
let numbers: number[] = [1, 2, 3];let names: Array<string> = ["A", "B", "C"];Both ways of writing an array type are correct, you can use whichever one you like.
let matrix: number[][] = [ [1, 2], [3, 4],];This is simply an array that holds other arrays inside it, like a grid or table of numbers.
A tuple is an array that has a fixed number of items, and each item has its own fixed type and fixed position.
let user: [string, number] = ["Sahil", 22];Here, the first item must always be a string and the second item must always be a number. The order matters.
Common use cases:
enum Status { Pending, Success, Failed,}Enums actually create real JavaScript code that runs when your program runs (this is called runtime output).
Modern alternative:
type Status = "pending" | "success" | "failed";This does the same job as an enum, but it does not add any extra JavaScript code when it runs.
class Person { name: string;
constructor(name: string) { this.name = name; }}A class is like a blueprint for creating objects. Here, every Person object will have a 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; }}Access modifiers control where a property or method can be used from.
public
Can be accessed from anywhere, no restrictions.
private
Can only be accessed inside the same class.
protected
Can be accessed inside the class, and also inside any child class (subclass).
class MathUtil { static PI = 3.14159;}
const value = MathUtil.PI;Static members belong to the class itself, not to any single object created from that class. This means you do not need to create a new MathUtil object just to use PI, you can use it directly on the class.
abstract class Animal { abstract makeSound(): void;}
class Dog extends Animal { override makeSound(): void { console.log("Woof"); }}An abstract class is a class that cannot be used directly to create objects. It is meant to be a base class that other classes build on top of. Here, Animal says that every animal must have a makeSound method, but it does not say what that sound actually is, each child class decides that for itself.