Search code examples
javascriptjsdoc

Type hinting for an identity function


I want to type a defection for a function which returns its passed argument, the argument could be of any type, the important thing is to reflect the interface of the argument to the return value.

For example on line 6 in the image below, I want to type z. and then immediately I want the code editor to show me auto-completion, so it should show the option a.

enter image description here

How to define this in JSDoc?

Since typescript inference can't detect this, and I'm using VS Code, and since I'm using vanilla JavaScript so how to make it in JsDoc?

function returnMe(x) {
  return x
}

const z = returnMe({a:2})
z. // 👈 here I want to get auto completion 

Solution

  • Does this do it? From https://medium.com/@antonkrinitsyn/jsdoc-generic-types-typescript-db213cf48640.

    /**
     * @template A
     * @param {A} val
     * @returns {A}
     */
    function ident(val) {
      return val;
    }