Search code examples
javascripttypescriptvariable-assignment

How to properly use spread opeartor in Javascript/Typescript


I have two objects with two different types, I want to use one object to assign another.

interface From {
  type: string;
  timestamp: number;
  aid?: string;
  bid?: string;
  cid?: string;
  did?: string;
  eid?: string;
  fid?: string;
  gid?: string;
}

interface To {
  fromSocketID: string;
  type: string;
  timestamp: number;
  aid?: string;
  bid?: string;
  cid?: string;
  did?: string;
  eid?: string;
  fid?: string;
}

const from: From = {
  type: "aaa",
  timestamp: 1231231231,
  gid: "ddd"
};

// Method1
const to1: To = {
  fromSocketID: "temp",
  type: from.type,
  timestamp: from.timestamp
};
if (from.aid) {
  to1.aid = from.aid
}
if (from.bid) {
  to1.bid = from.bid;
}
if (from.cid) {
  to1.cid = from.cid;
}
// ...three more if statements

// Method2
const to2: To = {
  fromSocketID: "temp",
  ...from
}
// @ts-ignore
delete to2.gid;

interface To has a fromSocketID which From doesn't, and To lacks a gid property. In my real work scenario, I use Method1. I tried Method2, but i had to use ts-ignore. I wonder if there is a better solution.


Solution

  • You can use the rest operator to deconstruct the 'from', ignoring the gid property, like so:

    interface From {
      type: string;
      timestamp: number;
      aid?: string;
      bid?: string;
      cid?: string;
      did?: string;
      eid?: string;
      fid?: string;
      gid?: string;
    }
    
    interface To {
      fromSocketID: string;
      type: string;
      timestamp: number;
      aid?: string;
      bid?: string;
      cid?: string;
      did?: string;
      eid?: string;
      fid?: string;
    }
    
    const from: From = {
      type: "aaa",
      timestamp: 1231231231,
      gid: "ddd"
    };
    
    const { gid, ...rest } = from;
    
    const to: To = {
      fromSocketID: "temp",
      ...rest
    };