All academies

Properties

Instance fields, optional properties, and readonly state.

12 minLevel 5 of 20

Instance properties

Properties (fields) store per-instance state. TypeScript lets you declare types, optionality (?), and definite assignment.

Fields
class Profile {
  bio?: string;
  constructor(public username: string) {}
}
const p = new Profile("ada");
console.log(p.username, p.bio);
p.bio = "Mathematician";
console.log(p.bio);

readonly and immutability

readonly prevents reassignment after construction — perfect for IDs and injected collaborators (private readonly).

readonly
class Order {
  constructor(public readonly id: string, public total: number) {}
}
const o = new Order("o1", 10);
o.total = 12;
console.log(o.id, o.total);
// o.id = "x"; // compile error if uncommented

Getters as derived properties

Use get for computed views of state without exposing raw fields — a step toward encapsulation.

Getter
class Cart {
  constructor(private items: number[]) {}
  get count() { return this.items.length; }
  get total() { return this.items.reduce((a, b) => a + b, 0); }
}
const c = new Cart([10, 15, 5]);
console.log(c.count, c.total);

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

readonly means: