iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Classes

TypeScript classes are JavaScript classes plus typed fields, access modifiers, and parameter properties. They compile to standard JS classes.

Basics

TS
class Person {
    name: string;
    age:  number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age  = age;
    }

    greet(): string {
        return `Hi, I am ${this.name}`;
    }
}

const p = new Person('Ada', 36);
console.log(p.greet());

Parameter properties (shorthand)

Declare and assign in one shot — by far the most common pattern:

TS
class Person {
    constructor(
        public  name: string,
        public  age:  number,
        private secret = '',
    ) {}

    greet() { return `Hi, ${this.name}`; }
}

Readonly fields

TS
class Money {
    constructor(public readonly cents: number, public readonly currency = 'USD') {}
}

const m = new Money(1000);
// m.cents = 2000;   // ✗ error

Static members

TS
class MathUtils {
    static readonly PI = 3.14159;

    static square(n: number): number {
        return n * n;
    }
}
MathUtils.square(5);

Index signatures on classes

TS
class Dictionary {
    [key: string]: string;
    add(k: string, v: string) { this[k] = v; }
}

Generic classes

TS
class Box<T> {
    constructor(public value: T) {}
    map<U>(fn: (v: T) => U): Box<U> {
        return new Box(fn(this.value));
    }
}
Tip: Constructor parameter properties save a lot of typing — declare and assign at once with public readonly name: string. Modern style prefers them.

Example

Example
class Account {
  constructor(
    public readonly owner: string,
    private balance = 0,
  ) {}

  deposit(amount: number) {
    this.balance += amount;
    return this;
  }
  getBalance() { return this.balance; }
}

const a = new Account('Ada');
console.log(a.deposit(50).deposit(30).getBalance());   // 80
Try it Yourself »

Exercise

Modifier that makes a field set-once.

public id: number;

Test yourself

Q1. Parameter property shorthand declares and assigns in…
Q2. readonly fields can be set…
Q3. Generic classes use…

Discussion

Loading…