如何优雅地填充缺失的对象参数?

How can I fill up missing object parameters in an elegant way?

我在使用初始参数时遇到问题(我不确定是否有打字稿解决方案或者它只是一个 JavaScript 问题,所以我向您展示与您等效的 Javascript):

const helloWorldWithOptions = (options = { a:1, b:2 } ) => {
  console.log("Hello World!")
};

使用函数时:

helloWorldWithOptions( {a:4} );

Typescript 说我在使用该函数时缺少对象键 b。我期望的是 js/ts 用初始参数填充缺失值。如果已经有最先进的技术,请告诉我。

您可以使用 the Partial type and ... spreading 将您的默认设置与调用者的覆盖相结合。

TS playground

const defaults = { a: 1, b: 2 };

// Could use a named type instead of `typeof defaults` too.
const helloWorldWithOptions = (options: Partial<typeof defaults> = {}) => {
  const mergedOptions = { ...defaults, ...options };
  console.log(mergedOptions);
};
helloWorldWithOptions({ a: 3 });

您可以在声明函数时指定默认值:

function aFunction({a = 1, b = 2}) {console.log(a, b)}

aFunction({}) //prints "1 2"

在这种情况下,'aFunction' 接收一个对象,每当您使用空对象调用该函数时,它会自动填充空白字段。 或者,您可以使用所需的参数调用 'aFunction',例如:

aFunction({a: 2, b: 3}) //prints "2 3"