英文:
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's quite odd that you can't do:
```ts
const createSomething = (
someRange: number[],
{ option }?: { option?: boolean } // INVALID
) => {}
so you have to do:
const createSomething = (
someRange: number[],
{ option }: { option?: boolean } = {}
) => {}
but then when you hover over createSomething
, it shows the signature as the former???
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 } = {}
) => {
console.log(option);
};
createSomething([1]); // Compiles and displays false
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论