I have the following object. The data comes in from 2 separate messages, both of which have a timestamp and icao (id number). However, one message has ident info (callsign) and the other has aircraft position.
export interface AircraftInfo {
timestamp: Date
icao: string
ident?: {
callsign: string
}
pos?: {
lat: number
lon: number
altitude: number
}
}
As the data comes in, I update the necessary sections. What’s the most elegant way to update the pos
property? I suspect if it already exists, the best thing to do is to update individual properties rather than overwriting with a new object. If it doesn’t, a new object has to be assigned.
This results in code like this:
// update position if position exists, otherwise create position with position
if (info.pos) {
info.pos.altitude = altitude
info.pos.lon = lon
info.pos.lat = lat
} else {
info.pos = { altitude, lon, lat }
}
This feels a little clunky. Is there a better way to do this?
2
Answers
I think this is less "clunky"
I am not sure, but you may need a spread operator (this apprach brings immutability as well):
https://stackblitz.com/edit/typescript-wbc2w2?file=index.ts