Interfaces

Rook — 1.0 specification

An interface describes the shape of a value: its fields and methods. As in TS, it exists only at compile time.

interface Shape {
    name string
    area() number
}

interface Point {
    x, y number
    label ?string                  // an optional field: it may be left out
}

class Circle implements Shape {
    name = "circle"
    r number

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

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

func describe(s Shape) string {
    return `${s.name}: ${s.area()}`
}

describe(new Circle(2))               // the class fits Shape
const p Point = { x: 1, y: 2 }        // the object literal fits Point

implements is optional: a class fits an interface if it has the needed fields and methods. implements just asks the compiler to check that where the class is declared.

Markdown source on GitHub