Web Analytics

TypeScript Classes

Beginner~25 min

Classes are blueprints for creating objects with properties and methods. TypeScript classes add type safety to JavaScript's class syntax, making object-oriented programming more robust.

TypeScript Class Structure

Basic Class Syntax

A class defines properties (data) and methods (behavior) for objects:

Output
Click Run to execute your code
Class Components:
  • Properties: Variables that hold data
  • Constructor: Special method that initializes objects
  • Methods: Functions that define behavior
  • this: Refers to the current instance

Properties and Methods

Properties store state, methods define behavior:

Output
Click Run to execute your code
Best Practice: Always type your class properties. This provides autocomplete and catches errors early.

The Constructor

The constructor runs when creating a new instance:

Output
Click Run to execute your code

Constructor Rules

  • Named constructor (not the class name)
  • Only ONE constructor per class
  • Automatically called with new
  • Can have parameters with default values

Class vs Interface

Feature Class Interface
Creates objects โœ“ Yes โœ— No
Has implementation โœ“ Yes โœ— No
Can be instantiated โœ“ Yes โœ— No
Runtime presence โœ“ Yes โœ— No (compile-time only)
Use case Create objects Define contracts

Common Mistakes

1. Forgetting 'new' Keyword

class Person {
    constructor(public personName: string) {}
}

// โœ— Wrong - calling class like a function
let person = Person("Alice");  // Error!

// โœ“ Correct - use 'new'
let person = new Person("Alice");

2. Not Typing Properties

// โœ— Wrong - implicit 'any' type
class User {
    userName;  // any type!
}

// โœ“ Correct - explicit type
class User {
    userName: string;
}

3. Forgetting 'this' Keyword

class Counter {
    count: number = 0;
    
    increment() {
        count++;  // โœ— Wrong - 'count' is not defined
    }
    
    incrementCorrect() {
        this.count++;  // โœ“ Correct
    }
}
Important: Class properties are NOT initialized by default. Always initialize them in the declaration or constructor.

Summary

  • Classes are blueprints for creating objects
  • Properties store data with types
  • Methods define behavior
  • Constructor initializes new instances
  • Use new keyword to create instances
  • Always use this to access properties/methods

What's Next?

Next: Constructors in depth with parameter properties!