It has been a while since the last time I did some front end development. So my TypeScript skills are kinda rusty.
Today I tried to write the following code. In this code I'm subscribing to a Server-Send-Event and try to update an element on the screen(I'm not using Angular or any other framework for this small widget).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var source = new EventSource("https://localhost/notifications"); | |
var notification = document.getElementById("notification-count"); | |
source.onmessage = event => { | |
const count = event.data; | |
notification?.style?.visibility = count > 0 ? "visible" : "hidden"; | |
this.updateCount(count); | |
}; | |
source.onerror = error => { | |
console.log("Notification error", error); | |
notification?.style?.visibility = "hidden"; | |
} |
The TypeScript compiler didn't like this and returned the following error:
The left-hand side of an assignment expression may not be an optional property access
The reason is that I try to use the optional chaining (?.) operator on the left-hand side of an assignment. To solve the error, I have to use an if
statement that serves as a type guard instead before the assignment:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var source = new EventSource("https://localhost/notifications"); | |
var notification = document.getElementById("notification-count"); | |
source.onmessage = event => { | |
const count = event.data; | |
if(notification){ | |
notification.style.visibility = count > 0 ? "visible" : "hidden"; | |
} | |
this.updateCount(count); | |
}; | |
source.onerror = error => { | |
console.log("Notification error", error); | |
if(notification){ | |
notification.style.visibility = "hidden"; | |
} | |
} |