Start learning free

LESSON 612 OF 639 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in TypeScript in TypeScript

Lesson

TL ; DR:

For objects, === asks if two variables hold the very same object. TypeScript can't change that. The convention is an equals(other) method that compares the values. For a Set or a Map, a key() method turns the object into a string.


equals(other: Time): boolean {
    return this.hour === other.hour && this.minute === other.minute;
}

key(): string {
    return this.hour + ":" + this.minute;
}


Full lesson:

Two objects can hold the same values and still be two objects. Create new Time(9, 30) twice, as a and b. Then a === b is false.

For objects, === checks identity. It is true only when both variables hold one and the same object. There is no way to change what it means for your class.

Equal by value

So you write a method for it. By convention it is equals(other). It returns true when the fields match. You call it yourself, as a.equals(b).

Sets and maps need a key

A Set compares objects by identity too. Two equal times would be two items. So store a string instead.

A key() method builds it from the same fields as equals. Strings compare by value. Equal times give the same key, and the set keeps it once.

Keep the fields apart

Put a separator between the fields in the key. Without it, 1 and 23 give "123", and so do 12 and 3.


Your task

The Time class keeps an hour and a minute. Give it equals(other) and key(). Two times are equal when the hour and the minute both match. The key is the hour, a colon, then the minute.

The code below the class compares three times. Then it adds their keys to a Set of alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in TypeScript

    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free