Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active April 14, 2021 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagenorhynque/b9fd4b85ed9839e81216aac4401f8bdb to your computer and use it in GitHub Desktop.
Save lagenorhynque/b9fd4b85ed9839e81216aac4401f8bdb to your computer and use it in GitHub Desktop.
Subtyping, inheritance and delegation
class Quadrangle {
name: string;
width: number;
height: number;
constructor(name: string, width: number, height: number) {
this.name = name;
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
// delegation
class Rectangle {
quad: Quadrangle;
constructor(name: string, width: number, height: number) {
this.quad = new Quadrangle(name, width, height);
}
get name(): string {
return this.quad.name;
}
getArea(): number {
return this.quad.getArea();
}
}
const rectangles = [new Rectangle("A", 100, 100), new Rectangle("B", 10, 10)];
console.log(
rectangles.map((rectangle) => ({ [rectangle.name]: rectangle.getArea() }))
);
class Quadrangle {
name: string;
width: number;
height: number;
constructor(name: string, width: number, height: number) {
this.name = name;
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
// implementation inheritance
class Rectangle extends Quadrangle {
constructor(name: string, width: number, height: number) {
super(name, width, height);
}
}
const rectangles = [new Rectangle("A", 100, 100), new Rectangle("B", 10, 10)];
console.log(
rectangles.map((rectangle) => ({ [rectangle.name]: rectangle.getArea() }))
);
interface Shape {
name: string;
getArea(): number;
}
// subtyping (interface inheritance)
class Rectangle implements Shape {
name: string;
width: number;
height: number;
constructor(name: string, width: number, height: number) {
this.name = name;
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
class Cricle implements Shape {
name: string;
radius: number;
constructor(name: string, radius: number) {
this.name = name;
this.radius = radius;
}
getArea(): number {
return this.radius * this.radius * 3.14;
}
}
const shapes: Shape[] = [
new Rectangle("A", 100, 100),
new Rectangle("B", 10, 10),
new Cricle("C", 30),
];
console.log(shapes.map((shape) => ({ [shape.name]: shape.getArea() })));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment