#typescript
#oop
#classes
Day 8: Introduction to Classes
Phase 2: Object-Oriented TypeScript
Welcome to Phase 2! We are moving from functional scripts to structured, object-oriented applications. The core of OOP is the Class.
What is a Class?
A class is a blueprint for creating objects. You define the properties (data) and methods (behavior) that the objects will have.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
Creating Instances
To use the class, we create an instance of it using the new keyword.
const jack = new Person("Jack", 25);
jack.greet(); // "Hello, my name is Jack."
The this Keyword
Inside a class, this refers to the current instance of the object. this.name accesses the name property of that specific person.
Initialization & Strict Property Initialization
TypeScript is strict. If you declare a property like name: string, you must initialize it in the constructor.
class Car {
model: string; // Error: Property 'model' has no initializer...
}
To fix this, either:
- Initialize it in the constructor.
- Give it a default value:
model: string = "Toyota";. - Mark it as optional:
model?: string;. - Use the Definite Assignment Assertion (not recommended for beginners):
model!: string;.
Challenge for Today
- Create a class
Calculator. - It should have no properties.
- Add methods
add(a, b),subtract(a, b),multiply(a, b),divide(a, b). - Type the parameters and return values properly.
- Create an instance and calculate
add(5, 10).
See you on Day 9, where we control access with Access Modifiers!