首页 > 解决方案 > 打字稿哈希成员算术限制

问题描述

我可以在打字稿中以某种方式定义一个类型,该类型也适用于对象道具的 arythmeical 约束,例如

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

所以a% b= 0

标签: typescript

解决方案


不,这需要运行时检查,这超出了 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 代替。


推荐阅读