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?