Rook
РусскийRU

Classes and interfaces

Classes are as in TypeScript: typed fields, constructor, extends, the private and protected modifiers. If the board needs task behavior alongside task data, a class can encapsulate both; using a class is an organization choice, not a requirement for every record.

Interfaces are structural: a class or an object fits if it has the fields and methods. implements only asks the compiler to check that where the class is declared.

interface Shape {
    area() number
}

class Circle implements Shape {
    private radius number

    constructor(radius number) {
        this.radius = radius
    }

    area() number {
        return Math.PI * this.radius ** 2
    }
}

class Square implements Shape {
    private side number

    constructor(side number) {
        this.side = side
    }

    area() number {
        return this.side * this.side
    }
}

// Interfaces are structural: any object with an area() method fits
const shapes Shape[] = [new Circle(1), new Square(2), { area: () => 10 }]
for shape in shapes {
    console.log(shape.area().toFixed(2))
}

Getters and setters are written as in JS, with get and set, and are read and assigned as fields. A readonly field is assigned only in the constructor, and a constructor parameter with private, public or readonly is a field too. An abstract class has no instances of its own; its abstract methods have no body, and each subclass implements them.

abstract class Shape {
    // A parameter with readonly is also a field, which the constructor assigns
    constructor(readonly name string) { }

    // An abstract method has no body: each subclass implements it
    abstract area() number

    describe() string {
        return `${this.name}: ${this.area().toFixed(2)}`
    }
}

class Circle extends Shape {
    constructor(private r number) {
        super("circle")
    }

    area() number {
        return Math.PI * this.r ** 2
    }

    // A getter and a setter are read and assigned as a field
    get diameter() number {
        return this.r * 2
    }

    set diameter(value number) {
        this.r = value / 2
    }
}

const circle = new Circle(1)
circle.diameter = 4
console.log(circle.describe(), circle.diameter)
// new Shape("blob") and circle.name = "disc" are compile errors