需求是接收一个对象,指定此对象的某些属性,如果属性值为空,赋一个值,并且生成一个新对象。
代码:
import { cloneDeep } from 'lodash';function assignDefaults<T>(obj: T, def: Partial<T>): T {// 深拷贝let res = cloneDeep(obj);// 遍历指定属性for (let k in def) {// 给空属性赋值res[k] ??= def[k];}return res;
}export default assignDefaults;
使用:
const myObj: {id: number;name: string | null;address: string | undefined;age: number;
} = {id: 1,name: null,address: undefined,age: 30,
};const newMyObj = assignDefaults(myObj, {id: 22,name: 'Default Name',address: 'New York',age: 10,
});// 输出:{id: 1, name: 'Default Name', address: 'New York', age: 30}
console.log(newMyObj);