Using class instances as keys in a Typescript Map

Viewed 1072

When gettings and setting map values, the map has to somehow know wether the keys equal another, already set key.

How do I implement equality for complex datatypes (custom classes) in Typescript? In Java I would override the equals method, is there an equivalent in typescript?

In my case I have the following class:

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    --    ?

}

I want to use instances of this class as keys in a map like this:

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'
1 Answers

How do I implement equality for complex datatypes (custom classes) in Typescript?

You can't. Map is something TypeScript gets from JavaScript. The JavaScript specification says Map uses the SameValueZero operation to determine whether keys are equal to each other. With object instances, that's ===. That is, only the same instance is equal to itself, not equivalent instances. It doesn't defer to an object method like Java's collections can.

There's no built-in map-like structure that allows you to determine key equality. You can build one, but there's not one by default.

Related