简体   繁体   中英

How to define options for JavaScript object?

I have function that requires JS Object as one of the parameter. 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. In vscode, whenever we tried to pass the object, it auto-completes with options that can be passed like for code below

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"

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 . Your fancy shmancy editor will suggest number1 and number2

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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