我应该如何创建一个对象,仅当它们存在时才复制可选属性?
How should I create an object, copying optional properties only if they exist?
我正在编写在不同域之间映射对象的代码。通常,对象有多个可选字段,如果它们存在,我想复制它们。我在以下代码中的尝试:
createFrom1
:有效,但有很多重复。
createFrom2
:不起作用 - 可选属性变为 undefined
我怎样才能做到这一点?
interface type1 {
mandatoryX: string; // plus more...
optionalFoo?: string;
optionalBaz?: string
}
interface type2 {
mandatoryY: string; // plus more...
optionalBar?: string;
optionalBaz?: string
}
function createFrom(input: type1) : type2 {
const output : type2 = {
mandatoryY: input.mandatoryX,
};
if (input.optionalFoo != null) {
output.optionalBar = input.optionalFoo;
}
if (input.optionalBaz != null) {
output.optionalBar = input.optionalBaz;
}
return output;
}
function createFrom2(input: type1) : type2 {
return {
mandatoryY: input.mandatoryX,
optionalBar: input.optionalFoo, // Doesn't work right - if input.optionalFoo is not defined, will create optionalBar: undefined
optionalBaz: input.optionalBaz,
};
}
您可以使用 Spread syntax:
来实现
function createFrom2(input: type1) : type2 {
return {
mandatoryY: input.mandatoryX,
...input.optionalFoo && { optionalBar: input.optionalFoo },
...input.optionalBaz && { optionalBaz: input.optionalBaz },
};
}
我正在编写在不同域之间映射对象的代码。通常,对象有多个可选字段,如果它们存在,我想复制它们。我在以下代码中的尝试:
createFrom1
:有效,但有很多重复。createFrom2
:不起作用 - 可选属性变为undefined
我怎样才能做到这一点?
interface type1 {
mandatoryX: string; // plus more...
optionalFoo?: string;
optionalBaz?: string
}
interface type2 {
mandatoryY: string; // plus more...
optionalBar?: string;
optionalBaz?: string
}
function createFrom(input: type1) : type2 {
const output : type2 = {
mandatoryY: input.mandatoryX,
};
if (input.optionalFoo != null) {
output.optionalBar = input.optionalFoo;
}
if (input.optionalBaz != null) {
output.optionalBar = input.optionalBaz;
}
return output;
}
function createFrom2(input: type1) : type2 {
return {
mandatoryY: input.mandatoryX,
optionalBar: input.optionalFoo, // Doesn't work right - if input.optionalFoo is not defined, will create optionalBar: undefined
optionalBaz: input.optionalBaz,
};
}
您可以使用 Spread syntax:
来实现function createFrom2(input: type1) : type2 {
return {
mandatoryY: input.mandatoryX,
...input.optionalFoo && { optionalBar: input.optionalFoo },
...input.optionalBaz && { optionalBaz: input.optionalBaz },
};
}