skip to Main Content

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


  1. I think this is less "clunky"

    if (!info.pos) info.pos = {};
    info.pos.altitude = altitude;
    info.pos.lon = lon;
    info.pos.lat = lat;
    
    Login or Signup to reply.
  2. 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

    interface AircraftInfo {
      timestamp: Date;
      icao: string;
      ident?: {
        callsign: string;
      };
      pos?: {
        lat: number;
        lon: number;
        altitude: number;
      };
    }
    
    const aircraftInfo: AircraftInfo = {
      timestamp: undefined,
      icao: '',
    };
    
    aircraftInfo.ident = {
      ...aircraftInfo.ident,
      callsign: 'callsign',
    };
    
    aircraftInfo.pos = {
      ...aircraftInfo.pos,
      lat: 1,
      lon: 2,
      altitude: 3,
    };
    
    console.log(aircraftInfo);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search