简体   繁体   English

如何为 JavaScript 对象定义选项?

[英]How to define options for JavaScript object?

I have function that requires JS Object as one of the parameter.我有需要 JS 对象作为参数之一的函数。 And what I wanted to do is define options that can be passed inside that object.我想做的是定义可以在该对象内部传递的选项。 Let me explain what I meant with an example All of us are familiar with fetch() in js.让我用一个例子来解释一下我的意思我们都熟悉 js 中的 fetch()。 In vscode, whenever we tried to pass the object, it auto-completes with options that can be passed like for code below在 vscode 中,每当我们尝试传递对象时,它都会使用可以传递的选项自动完成,如下面的代码

fetch(url, {

})

when I type say m inside {}, it suggests all available options start with the letter m (method) and when pressed enter we get something like method: "GET"当我在 {} 中输入 say m 时,它建议所有可用的选项都以字母 m(方法)开头,当按下回车键时,我们会得到类似method: "GET"

I wanted to achieve a similar feature with my function.我想用我的功能实现类似的功能。

I didn't know what am I suppose to look for to get my solution so I have only done a little research with the closest possible query for me on google but I didn't get any solution for this particular problem.我不知道我应该寻找什么来获得我的解决方案,所以我只对谷歌上最接近的查询进行了一些研究,但我没有得到任何解决这个特定问题的方法。

Just a hint or direction will be fine只是一个提示或方向就可以了

This is your editor's intellisense hard at work.这是您的编辑在努力工作的智能感知。 If you want to achieve the same thing, just immediately destructure the object you're expecting as a parameter.如果您想实现相同的目标,只需立即解构您期望作为参数的对象。

Try calling this function, giving it an object as an argument and type the letter n .尝试调用这个函数,给它一个对象作为参数并输入字母n Your fancy shmancy editor will suggest number1 and number2你花哨的 shmancy 编辑器会建议number1number2

const myFunction = ({ number1, number2 }) => {
    return number1 + number2;
};

You can also do this without the immediate destructuring by using TypeScript (and ensuring your editor supports TypeScript - if you're using VSCode then it does):您也可以通过使用 TypeScript 来执行此操作而无需立即解构(并确保您的编辑器支持 TypeScript - 如果您使用的是 VSCode,那么它会支持):

interface Options {
    number1: number;
    number2: number;
}

const myFunction = (options: Options) => {
    return options.number1 + options.number2;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM