Use TypeScript classes with constructors, methods, and access modifiers.
TypeScript adds static typing to JavaScript's class syntax, making object-oriented code safer and more expressive.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): string {
return `${this.name} makes a sound`;
}
}
const dog = new Animal('Rex');
console.log(dog.speak()); // "Rex makes a sound"
public (default) — accessible anywhereprivate — only inside the class bodyprotected — inside the class and subclassesclass BankAccount {
private balance: number;
constructor(initial: number) {
this.balance = initial;
}
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
TypeScript lets you declare and assign properties in one line:
class Point {
constructor(public x: number, public y: number) {}
}
const p = new Point(3, 4);
Create a Rectangle class with:
width and height number properties set via the constructorarea() method returning width * heightperimeter() method returning 2 * (width + height)Export the class as the default export.
// Create a Rectangle class with width, height, area(), and perimeter() // Export it as the default export
No test results yet
Click Run Tests or press Ctrl+Enter