TypeScript Course
TypeScript
/
Beginner

Classes

Definition

TypeScript adds powerful static typing, access modifiers, and type-checking capabilities to standard ES6 JavaScript Classes.

Explain Like I'm New

A Class in JavaScript is a factory for creating objects. TypeScript turns that factory into a high-security facility. It ensures every worker (property) is accounted for, makes sure people can't enter restricted areas (private properties), and ensures the final product exactly matches the blueprint.

Real World Example

Building an API service layer: `class UserService { fetchUser() { ... } }`.

Common Use Cases

  • •Object-oriented architecture
  • •Encapsulating state and behavior together

Interactive Example

class Player {
  // 1. MUST declare types here first!
  name: string;
  score: number;

  constructor(playerName: string) {
    this.name = playerName;
    this.score = 0; // Initialization required by TS
  }

  addScore(points: number): void {
    this.score += points;
  }
}

const p1 = new Player("Alice");
p1.addScore(10);

// Parameter Properties Shorthand (Extremely popular!)
// By adding 'public' or 'private' to the constructor argument, 
// TS automatically declares AND assigns the property behind the scenes!
class FastPlayer {
  constructor(public name: string, public score: number = 0) {}
}

Interview Questions

basic

  • Do you need to declare class properties before using them in the constructor in TS?

intermediate

  • What is Parameter Properties shorthand?

advanced

  • What does `strictPropertyInitialization` do in tsconfig?

Flash Cards

Question

Do you need to declare properties first?

Click to reveal answer
Answer

Yes! In vanilla JS, you can just do `this.name = name` in the constructor. In TS, you MUST declare `name: string;` at the top of the class body before using it in the constructor (unless using shorthand).

Question

What is strictPropertyInitialization?

Click to reveal answer
Answer

If this flag is true, TS throws an error if you declare a class property (like `name: string;`) but forget to actually assign it a value inside the `constructor()`. It prevents undefined bugs.