如何在 Javascript/Typescript 中正确使用展开运算符

How to properly use spread opeartor in Javascript/Typescript

我有两个不同类型的对象,我想用一个对象赋值给另一个对象。

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 有一个 fromSocketIDFrom 没有,To 没有 gid 属性。在我的实际工作场景中,我使用的是Method1。我尝试了 Method2,但我不得不使用 ts-ignore。请问有没有更好的解决办法

你可以使用剩余运算符来解构'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
};