Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a generic type argument with JSDoc?

Before giving up I wanted to give it a shot here.

I have a definition file with typings like the following:

/**
 * My json decode function, in reality very different
 * implementation (class like) but it works as an example
 */
  function decodeJSON<T = unknown>(str: string): T;

If I wanted to use this generic in TypeScript I would do something like the following

const value = decodeJSON<number[]>("[1,2,3]"); // return type will be number[]

However in my actual code I can't use TypeScript, only it's typings for development purposes, and I can't seem to find a way to tell my editor what the type I'm passing to the generic parameter is so that I get the correct type information.

I've tried to use JSDoc to specify what the parameter for the generic might be the same way that TypeScript can

// I was expecting JSDoc to understand something like this, but it doesn't
/** @type {decodeJSON<number[]>} */
const value = decodeJSON("[1,2,3]"); // Type inference will be unknown

But it doesn't work. I don't really care what the result might be in runtime, I have sanity checks for that already implemented. I just want my editor to give me type hints about the generic function result to make my job (this function has some heavy use in my app) easier

My editor is WebStorm in case it matters, but this seems to be a general limitation of JSDoc

like image 308
Steven Guerrero Avatar asked Nov 20 '25 10:11

Steven Guerrero


2 Answers

Apparently this isn't something that JSDoc can do, even though the need for it is kinda real

https://github.com/microsoft/TypeScript/issues/27387

like image 101
Steven Guerrero Avatar answered Nov 22 '25 04:11

Steven Guerrero


My 2 cents if someone came here searching how to type a ts Generic <T> using JsDoc;

this ts

function identity<T>(arg: T): T {
  return arg;
}

could be achieved as:

/**
 * @template T
 * @param {T} arg
 * @return {T}
 */
function identity(arg) {
  return arg;
}

then:

identity({value: 42}).
                     ^ suggests value: number
like image 27
Manu Avatar answered Nov 22 '25 04:11

Manu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!