TypeScript-Handbook icon indicating copy to clipboard operation
TypeScript-Handbook copied to clipboard

Document JSDoc imports with generics

Open gregtatum opened this issue 5 years ago • 5 comments

The JSDoc types do not include an example of importing a type with a generic.

e.g. this is the correct way:

/**
 * @template T
 * @typedef {import("../types").ThunkAction<T>} ThunkAction<T>
 *

I won't enumerate the wrong ways I tried :D

It took me a good hour to figure it out, with lots of searching. I could not find any examples anywhere in the docs, nor in Stack Overflow. I figured someone else could benefit from my confusion.

gregtatum avatar Sep 13 '19 19:09 gregtatum

Thank-you, this helped me loads after a lot of searching.

I'm new to JSDoc and using vscode. Another gotcha for me was that this restricts typeDef other types in the same jsdoc as a template variable:

The following makes Bob generic too:

/**
 * @template T
 * @typedef {import("../types").ThunkAction<T>} ThunkAction<T>
 * @typedef {import("../types").Bob} Bob
 */

The following makes Bob generic and also adds a Cannot find name 'T' error:

/**
 * @typedef {import("../types").Bob} Bob
 * @template T
 * @typedef {import("../types").ThunkAction<T>} ThunkAction<T>
 */

It also seems like the second param on the type def is optional, as the following also works for me:

/**
 * @template T
 * @typedef {import("../types").ThunkAction<T>} ThunkAction
 */

I assume these aren't defects, but I found this quite confusing and additional documentation might help?

andrewrlee avatar Oct 19 '19 07:10 andrewrlee

Thanks for clarifying some of those points @andrewrlee, I ran into some of those issues as well.

gregtatum avatar Oct 24 '19 20:10 gregtatum

@gregtatum wow thank you so much!! 👏👏 👏

codingedgar avatar Dec 13 '19 15:12 codingedgar

I want to know how to keep the generic when useing typedef to import: screenshot_2020-02-13_17-08-58

tjx666 avatar Feb 13 '20 09:02 tjx666

@tjx666

/** line 3
 * @template T
 * @typedef {import('./node').Node<T>} Node
 */

. . . 
  / **                                      // line 15 
    * @template T
    * @type {Node<T> | undefined}
    */
  this.head = undefined                     // line 16

sultan99 avatar Jun 06 '20 17:06 sultan99