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

Loading Code Playground...

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.