0

I have a custom class called Foo:

class Foo {
    constructor(public v: any) {
    }
}

And I have a map where Foo is my Key:

const map = new Map<Foo, string>();

AFAIK TypeScript doesn't have comparision overloading. How can I make sure that getting the key works properly?

const foo = new Foo(1234);
map.get(foo);

Here is the entire code:

class Foo {
    constructor(public v: any) {

    }
}

const map = new Map<Foo, string>();


const foo = new Foo(1234);
map.set(foo, "HELLO WORLD");

const foo2 = new Foo(1234);
console.log(map.get(foo2)); // DOESN'T work

console.log(map.get(foo)); // DOES work of course

You can find my problem here: https://www.typescriptlang.org/play?#code/MYGwhgzhAEBiD29oG8BQ0PWPAdhALgE4Cuw+8hAFAA7EBGIAlsNAG4Bc0YOAngJQpU6TAF9UYodjz5oAWzDVoAXmg4ApgHdoAWQUAeBPAA00AoUY4A5gD5KfANxDUUgtABmiZas1xElAIwATADMACwOqPLUAHQQaviUHsbQAEQAEgCiADJZAPLQAOq5AEpZACIpEZK4rkmBXupahgEh4Y4u8CBq0SDwlpRR0ZbxiYiBfA7QAPRT0AAm8GoQOADkMhoUANZOHV09fQMKQyNJE-bTs2W5GQDK0BuE26hAA

4
  • you didnt set foo2 on map or am I missing the point... Commented Jan 15, 2021 at 5:48
  • Thats the point. Both objects are same in value and therefore equal for my usecase Commented Jan 15, 2021 at 5:49
  • well {} !== {} in js, thats why, right? Commented Jan 15, 2021 at 5:50
  • Correct but thats not the end. If there would be no workarounds any Array.find() function would loose its purpose. Thats why such function has a custom "find" callback function Commented Jan 15, 2021 at 5:54

1 Answer 1

1

The problem you have isn't related to TypeScript, but rather JavaScript not having referential transparency. Therefore comparison like this new Foo(123) === new Foo(123) is always falsy.

Solution

The JavaScript's Map has a rather limited api. If you want to find specific entry using custom comparison function (in this case comparing by value), I'd suggest using .entries() method to get all the entries from the Map in form of an array of tuples [key, value][]. You can then find there whatever entry you want using Array.find(). The Map itself doesn't have any such method.

However, even better approach would be to rethink your data structure. Considering the limitations of the Map it would be better to have a primitive data type as a key in the Map. Since I don't know the specifics of your case I can only offer this general suggestion.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.