【发布时间】: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