0

I need to add a function attached to a node in this way:

myElement = querySelector('#myElement');
myElement.moveMe = () =>{
    //move Me Code;
}

But I do not know how to document this function (and also prevent lint errors), I tried use @extends with a @typedef but it says that it just works with constructors.

2 Answers 2

1

I might suggest that the right way to do this would be to create an object with {el: myElement, moveMe: ()=>{}} myself, but if you must extend, it looks like this:

/** 
 * @constructor
 * @extends {HTMLElement}
 */
const NewType = function() {};
/** @type {function()} */
NewType.prototype.moveMe = function(){};

/** @type {NewType} */
const myElement = /** @type {NewType} */ (document.querySelector('body div'));
myElement.moveMe = () =>{
    //move Me Code;
  console.log('dont remove me');
}

Error free

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I need to extend the HTMLElement because moveMe() has to be accessible when getting it by document.querySelector('.myElement').moveMe()
1

(Not sure about your stack, just noting my 2C from recent (2019-Q1) personal VSCode JSDoc struggles.)

In theory, it seems it should be possible to use simple @typedef with "parent" type declaration: (this does not work)

/**
 * @typedef {HTMLElement} movableElement
 * @property {function} moveMe
 */
/** @type movableElement */
var myElement = document.querySelector('#myElement');
myElement.moveMe; // NOPE, not present for some reason :(
myElement.tabIndex; // ok, this is from HTMLElement

Closest to intention of extending native HTML elements with custom properties was to & "Intersection Type notation" I learned about from this comment either using helper type:

/**
 * @typedef movable
 * @property {function} moveMe
 */
/**
 * @typedef {HTMLElement & movable} movableElement
 */
/** @type movableElement */
var myElement = document.querySelector('#myElement');
myElement.moveMe; // ok
myElement.tabIndex; // ok (HTMLElement properties are present as well)

Or even without helper type, with direct intersection:

/**
 * @typedef {HTMLElement & {moveMe: function}} movableElement
 */
/* ... */

Strangely, any @property declaration added to such extended type seems to be completely ignored (just like our property in the first failed attempt, I'm still not sure why).


I've been struggling to achieve something similar - extend HTMLElement with some hacky custom properties in JavaScript in VSCode - and after exhaustive SO / github / docs diving this workaround-ish solution quite worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.