Typescript中,类似Java SpringBoot中的BeanUtils.copyProperties方法:
在两个对象之间,按给定的属性名称数组来复制指定的属性值。
function copyProperties<T extends Object, U extends Object>(src: T, target: U, properties: (keyof T & keyof U)[]): void {
properties.forEach(prop => {
if (prop in src) {
(target as any)[prop] = src[prop];
}
});
}
interface Source {
aaa: string;
bbb: number;
ccc: boolean;
ddd: string;
eee: number;
}
interface Target {
aaa: string;
bbb: number;
ccc: boolean;
ddd: string;
fff: string;
}
const src: Source = {
aaa: 'hello',
bbb: 123,
ccc: true,
ddd: 'world',
eee: 456
};
const target: Target = {
aaa: '',
bbb: 0,
ccc: false,
ddd: '',
fff: 'not copied'
};
copyProperties(src, target, ["aaa", "bbb", "ccc", "ddd"]);
console.log(target);