TypeScript Classes
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.
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
newkeyword to create instances - Always use
thisto access properties/methods
What's Next?
Next: Constructors in depth with parameter properties!
Enjoying these tutorials?