【问题标题】:How to properly use spread opeartor in Javascript/Typescript [duplicate]如何在 Javascript/Typescript 中正确使用扩展运算符 [重复]
【发布时间】:2021-10-24 18:43:16
【问题描述】:

我有两个具有两种不同类型的对象,我想用一个对象分配另一个对象。

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 有一个 fromSocketID ,而 From 没有,To 缺少一个 gid 属性。在我的实际工作场景中,我使用 Method1。我尝试了 Method2,但我不得不使用ts-ignore。我想知道是否有更好的解决方案。

【问题讨论】:

    标签: javascript typescript variable-assignment


    【解决方案1】:

    您可以使用 rest 运算符来解构 'from',忽略 gid 属性,如下所示:

    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
    };
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2019-06-15
      • 1970-01-01
      • 2020-04-13
      • 1970-01-01
      • 2018-05-15
      • 2023-02-25
      • 2021-06-02
      • 1970-01-01
      相关资源
      最近更新 更多