【发布时间】:2020-07-13 08:12:04
【问题描述】:
当获取和设置地图值时,地图必须以某种方式知道键是否等于另一个已设置的键。
如何在 Typescript 中实现复杂数据类型(自定义类)的相等性?在 Java 中我会覆盖 equals 方法,打字稿中是否有等效方法?
就我而言,我有以下课程:
export class Path {
constructor(
private readonly scope: string[],
private readonly object: string[],
private readonly value: string
) { }
getScope(): string[] {
return this.scope;
}
getObject(): string[] {
return this.object;
}
getValue(): string {
return this.value;
}
// @override equals(): boolean -- ?
}
我想使用此类的实例作为映射中的键,如下所示:
const map = new Map<Path, string>();
map.set(new Path(['hello'], ['world'], 'asdf'), 'hwa');
map.set(new Path(['see', 'you'], ['world'], 'asdf'), 'swa');
map.get(new Path(['hello'], ['world'], 'asdf')); // 'hwa'
map.get(new Path(['see', 'you'], ['world'], 'asdf')); // 'swa'
【问题讨论】:
标签: typescript dictionary