预期需要2个参数,但只提供了1个 – 但我只想传递一个参数。

huangapple go评论101阅读模式
英文:

Expected 2 arguments but got 1 - but I want to pass just one

问题

我创建了一个具有以下签名的函数:

const createSomething = (
  someRange: number[],
  { option }: { option?: boolean }
) =>...

有时我只传递someRange参数给函数,有时传递额外的对象参数。然而,我收到一个错误,函数期望两个参数。如何将第二个参数声明为可选的?

英文:

I created a function with this signature:

  const createSomething = (
    someRange: number[],
    { option }: { option?: boolean }
  ) =>...

Sometimes I pass to the function just the someRange argument, and sometime the additional object argument. However I receive an error that the function expects two arguments. How can I declare the second argument to be optional?

答案1

得分: 4

const createSomething = (
    someRange: number[],
    { option }: { option?: boolean } = {}
) => {}

当你将鼠标悬停在 createSomething 上时,它显示的签名是前者???

无论如何,是的,你可以使用默认值来表示它是可选的。

在回顾中,为什么它无效现在显然很明显。如果第二个参数是 undefined,那么你无法解构它。


<details>
<summary>英文:</summary>

It&#39;s quite odd that you can&#39;t do:

```ts
const createSomething = (
    someRange: number[],
    { option }?: { option?: boolean } // INVALID
) =&gt; {}

so you have to do:

const createSomething = (
    someRange: number[],
    { option }: { option?: boolean } = {}
) =&gt; {}

but then when you hover over createSomething, it shows the signature as the former???

预期需要2个参数,但只提供了1个 – 但我只想传递一个参数。

Anyways, yeah, you can use a default value to show that it's optional.


In hindsight, it's quite obvious why it's invalid. If the second parameter is undefined, then you can't destructure it.

答案2

得分: 1

给你的选项对象一个默认值{},你也可以给option属性一个默认值:

const createSomething = (
    someRange: number[],
    { option = false }: { option?: boolean } = {}
) => {
    console.log(option);
};

createSomething([1]); // 编译并显示false
英文:

Give your options object a default value {}, you can also give the option property a default value as well:

const createSomething = (
    someRange: number[],
    { option = false }: { option?: boolean } = {}
) =&gt; {
    console.log(option);
};

createSomething([1]); // Compiles and displays false

huangapple
  • 本文由 发表于 2023年2月23日 23:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定