0

Background

I am creating a function that handles dom manipulation such as creating an element, adding/setting some properties on the element, and appending it to a parent. I wanted to use named parameters, but from my research I found that this feature is not built into JS. This stack overflow question helped me "simulate" named parameters with parameter destructuring and I was able to get it working successfully:

const createElement = function createNewDomElement({
        parent, 
        tag,
        idName, 
        className,
        innerHTML,
        href
    }={}) {
    
    if (parent) {
        console.log(parent);  // Works
    }

}

Visual studio code provides a hint that shows me which params are available:

enter image description here

Problem and Attempted Solution

As some of these parameters are required and the rest are optional, I would like to separate the optional parameters into a separate object within the function parameter object without losing the Visual Studio hint that shows which params are available. I tried to do this with:

const createElement = function createNewDomElement({
        tag,
        options: {
            parent, 
            idName, 
            className,
            innerHTML,
            href
        }
    }={}) {
    
    if (options) {
        options.forEach(item => console.log(item));
    }

}

However, when I try to access the options the same way as I was able to access the parent parameter in the first example, it says it is not defined.

Question

Is there a way to nest simulated named parameters in a way that maintains the Visual Studio Code hint showing which parameters are available?

I am also open to solutions which work, but where I lose the hint.

GeorgeCiesinski
  • 191
  • 1
  • 3
  • 11

1 Answers1

2

You won't be able to iterate those attributes but you can access it in this way

function createElement({
        tag,
        options: {
            parent, 
            idName, 
            className,
            innerHTML,
            href
        }
    } = { options: {} }) {
    
    if (parent) {
        console.log(parent)
    }
}
NirG
  • 746
  • 5
  • 12
  • Just to confirm, in your example I'm able to access `parent` from within options just using `parent` and not `options.parent`. Is it also possible to access `tag` and `options` the same way? Does this just take every object and nested object and create variables from their name/value pairs? – GeorgeCiesinski Dec 30 '22 at 02:11
  • 1
    Exactly, you can access `tag` in the same way but everything under `options` will be accessible by the attribute name only, so you cannot do `options.something` – NirG Dec 30 '22 at 10:25