TypeScript הגבלות חשבוניות על חברי Hash


האם אני יכול להגדיר איכשהו סוג ב-TypeScript שמתחיל גם מגבלות אריתמטיות על מאפייני האובייקט, לדוגמה.

type RestrictedObject = {
a: number,
b: number,
}

כך ש־a % b=0

תשובה #1

לא, זה ידרוש בדיקה בזמן ריצה, שזה מחוץ לתחום של TypeScript.

אתה יכול להגדיר אובייקט עם תכונות גישה כדי לאכוף את הקשר:

class Restricted {
    #a: number;
    #b: number;

    static #valid(a: number, b: number): boolean {
        return a % b === 0;
    }

    constructor(a: number,  b:number) {
        if (Restricted.#valid(a, b)) {
            throw new Error(`The values of 'a' and 'b' must be such that 'a % b' is 0; ${a} and ${b} don't fit`);
        }
        this.#a = a;
        this.#b = b;
    }

    get a() {
        return this.#a;
    }
    set a(value) {
        if (this.#b !== null) {
            if (Restricted.#valid(value, this.#b)) {
                throw new Error(`The value of 'a' cannot be ${value} when 'b' is ${this.#b}`);
            }
        }
        this.#a = value;
    }

    get b() {
        return this.#b;
    }
    set b(value) {
        if (this.#a !== null) {
            if (Restricted.#valid(this.#a, value)) {
                throw new Error(`The value of 'b' cannot be ${value} when 'a' is ${this.#a}`);
            }
        }
        this.#b = value;
    }
}

הערה צדדית: הדוגמה למעלה משתמשת בשדות פרטיים ובשיטות סטטיות פרטיות במבנה של JavaScript, שהם חלקים מוגדרים כעת בשפה, אבל אפשר להשתמש ב-private של TypeScript במקום אם רוצים.