TypeScript
Beginner
1 min read
Classes, Access Modifiers, and Parameter Properties
Example
// Parameter properties shorthand
class Person {
constructor(
public readonly id: number,
public name: string,
protected email: string,
private _passwordHash: string,
) {}
greet(): string {
return `Hi, I'm ${this.name}`;
}
}
// Abstract base class
abstract class Shape {
constructor(public readonly color: string) {}
abstract area(): number; // must be implemented
abstract perimeter(): number; // must be implemented
describe(): string {
return `A ${this.color} shape with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(color: string, public readonly radius: number) {
super(color);
}
area(): number { return Math.PI * this.radius ** 2; }
perimeter(): number { return 2 * Math.PI * this.radius; }
}
class Rectangle extends Shape {
constructor(
color: string,
public readonly width: number,
public readonly height: number,
) { super(color); }
area(): number { return this.width * this.height; }
perimeter(): number { return 2 * (this.width + this.height); }
}
const c = new Circle("red", 5);
const r = new Rectangle("blue", 4, 6);
console.log(c.describe()); // A red shape with area 78.54
console.log(r.describe()); // A blue shape with area 24.00
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript