Within my application, I have a requirement for mapping objects according to specific dates. Given that typescript provides both the Map
and Date
objects, I initially assumed this task would be straightforward.
let map: Map<Date, MyObject> = new Map<Date, MyObject>();
I thought I could simply utilize the set
method to insert new key-value pairs. However, upon implementation, I discovered that retrieving values using date keys required the exact same instance of Date
.
To verify this behavior, I wrote a unit test:
it('Experiencing an Issue', () => {
let d1: Date = new Date(2019, 11, 25); // Christmas day
let d2: Date = new Date(2019, 11, 25); // The same Christmas day?
let m: Map<Date, string> = new Map<Date, string>();
m.set(d1, "X");
expect(m.get(d1)).toBe("X"); // <- This works fine.
expect(m.get(d2)).toBe("X"); // <- This test fails.
});
This raises the question, why is it necessary to use the precise same instance in order to retrieve a value from the map?