Skip to content
TypeScript Essentials

TypeScript Classes

Beginner Lesson 5 of 9

TypeScript enhances JavaScript classes with type annotations and access modifiers.

class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, I'm ${this.name}`;
}
}
const person = new Person("Alice", 25);
class User {
public name: string; // Accessible anywhere
private password: string; // Only in this class
protected email: string; // This class and subclasses
constructor(name: string, password: string, email: string) {
this.name = name;
this.password = password;
this.email = email;
}
}
// Shorthand syntax
class User {
constructor(
public name: string,
private password: string,
readonly id: number
) {}
}
class Circle {
private _radius: number;
constructor(radius: number) {
this._radius = radius;
}
get radius(): number {
return this._radius;
}
set radius(value: number) {
if (value < 0) throw new Error("Radius must be positive");
this._radius = value;
}
get area(): number {
return Math.PI * this._radius ** 2;
}
}
class Animal {
constructor(public name: string) {}
speak(): void {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
speak(): void {
console.log(`${this.name} barks`);
}
}
abstract class Shape {
abstract area(): number;
abstract perimeter(): number;
describe(): string {
return `Area: ${this.area()}, Perimeter: ${this.perimeter()}`;
}
}
class Rectangle extends Shape {
constructor(public width: number, public height: number) {
super();
}
area(): number {
return this.width * this.height;
}
perimeter(): number {
return 2 * (this.width + this.height);
}
}
interface Printable {
print(): void;
}
class Document implements Printable {
constructor(public content: string) {}
print(): void {
console.log(this.content);
}
}

Continue to Generics →