我经常发现自己需要在TypeScrip中遍历一个大对象中的字段子集.我会经常使用析构来清理它,但我不喜欢重复的代码,即使它不是.有没有更好的办法让我失踪?
interface MyLargerObject {
field1: string;
field2: string;
field3: string;
field4: string;
field5: string;
field6: string;
field7: string;
field8: string;
field9: string;
otherField1: string;
otherField2: string;
otherField3: string;
otherField4: string;
otherField5: string;
}
interface MySmallerObject {
field1: string;
field2: string;
field3: string;
field4: string;
field5: string;
otherField1: string;
otherField2: string;
}
function subsetMethod(largerObject: MyLargerObject): MySmallerObject {
const {
field1,
field2,
field3,
field4,
field5
} = largerObject;
return {
field1,
field2,
field3,
field4,
field5,
otherField1: 'new1',
otherField2: 123
};
}
另外,我们假设MyLargerObject
和MySmallerObject
之间可能有重叠.我想确保我不会在这些情况下用largerObject
个值覆盖MySmallerObject
的重叠字段.