typescript - 打字稿哈希成员算术限制
问题描述
我可以在打字稿中以某种方式定义一个类型,该类型也适用于对象道具的 arythmeical 约束,例如
type RestrictedObject = {
a: number,
b: number,
}
所以a
% b
= 0
解决方案
不,这需要运行时检查,这超出了 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 代替。
推荐阅读
- c# - IIS 10 是否为并发请求生成多个线程?如果是这样,它在什么基础上决定是否产生一个新线程?
- mongodb - MongoDB changeStream 初始值
- python - 如何同时在 Python tkinter 中读取 csv?
- javascript - 如何通过 aws-sdk 方法 listObjects 获取文件夹
- flask - Flask socket io .on('event') 未处理,但 .on('message') 工作正常
- google-sheets - 在列中搜索常用文本字符串
- aws-lambda - SNS 未触发 Lambda
- mysql - 为什么sql比较忽略大小写
- java - Java 无法处理 π 字符
- javascript - 为了继续使用 Tensorflow.js 进行预测,在 Vue.js 实例中使用无限循环是错误的吗?