TypeScript | 给对象的空属性赋值

需求是接收一个对象,指定此对象的某些属性,如果属性值为空,赋一个值,并且生成一个新对象。

代码:

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);

猜你喜欢

转载自blog.csdn.net/m0_59449563/article/details/136063894