In my application, I need a map of objects per date. As typescript has both a Map
and a Date
objects, I expected this to be as easy as.
let map: Map<Date, MyObject> = new Map<Date, MyObject>();
And use set
to add new keys and values pairs. But then I've realized that I cannot get
the values using the dates, unless I use the exact same instance of Date
.
I've written a unit test with it:
it('Should not be a problem', () => {
let d1: Date = new Date(2019, 11, 25); // Christmas day
let d2: Date = new Date(2019, 11, 25); // Same Christmas day?
let m: Map<Date, string> = new Map<Date, string>();
m.set(d1, "X");
expect(m.get(d1)).toBe("X"); // <- This is OK.
expect(m.get(d2)).toBe("X"); // <- This test fails.
});
Why is it that I can't get the value from the map unless I use the exact same instance?