Classes & Decorators
Classes & Decorators: A TypeScript class is like a shortened form of the same Java pattern — in Java, assembling a piece of furniture means first declaring the part (a field), th
A TypeScript class is like a shortened form of the same Java pattern — in Java, assembling a piece of furniture means first declaring the part (a field), then bolting it on by hand (`this.field = value` inside the constructor); in TypeScript, writing `public` on a constructor parameter declares the field and bolts it on in a single automatic step. So if Java's two-step approach already works, why did TypeScript bother offering this shortcut? Because Java's type safety was already mandatory and the field/constructor distinction stayed clear without a shortcut; TypeScript, while preserving JavaScript's flexibility, has to deliver that same type safety with less repetition — more lines means more chances to forget something. The concrete QA payoff: a `TestContext` class with many fields like `browser`, `page`, `baseUrl` makes it easy to forget assigning one of them in a Java-style long constructor, and the bug only explodes at runtime the moment that field is accessed; TypeScript's `public` shortcut assigns every parameter automatically, structurally eliminating that risk of forgetting.
Micro Lab: TypeScript coding practice
Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.
TypeScript class anatomy
Constructor shorthand
public readonly id: number in constructor defines field — 1 line instead of 2 in Java
private, public, protected — same meaning as Java, less boilerplate
Inheritance and abstract
extends + abstract class — exact equivalent of Java extends and abstract
Order the steps of defining a TypeScript class:
Add public/private to constructor parameters
TypeScript auto-creates fields
Write return types for methods
Create subclass with extends