Search code examples
javascriptwebstormjsdoc

JSDoc: assign type to inline variable


Can I assign a type to a variable which gets a object result from a third party library?

const result = thirdPartyLib.doSomething();

Now I may have a ES6 class

class MyClass {
  ...
}

And I want to annotate my result to be of type MyClass.

Is this possible using JSDoc?


Solution

  • The JSDoc @type {…} tag can be applied to a local variable to declare its type.

    /** @type {MyClass} */
    const result = thirdPartyLib.doSomething();
    

    screenshot of WebStorm editor showing type-driven autocompletions after adding this tag

    However, instead of adding this declaration everywhere you call the function, you could use the @external tag to add JSDoc types to thirdPartyLib.doSomething(), allowing the local variable types to be inferred correctly.

    /**
     * @external thirdPartyLib
     */
    /**
     * @function external:thirdPartyLib.doSomething
     * @returns {MyClass}
     */
    
    const result = thirdPartyLib.doSomething();