microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.04k stars 12.49k forks source link

JSDoc doesnt support generics correctly #56102

Open thepassle opened 1 year ago

thepassle commented 1 year ago

🔎 Search Terms

jsdoc generics

🕗 Version & Regression Information

⏯ Playground Link

No response

💻 Code

Given the following code:

function api<T>(endpoint: string): Promise<T> {
  return fetch(endpoint).then(res => res.json());
}

When I consume the api function in a .js file, I'd still like to leverage the T generic via JSDoc-only. There currently isnt a straightforward way to do this, and the DX of this could definitely be improved.

🙁 Actual behavior

Cant leverage the T generic

🙂 Expected behavior

I can leverage the T generic

Additional information about the issue

This is a long overdue feature :)

fatcerberus commented 1 year ago

Not directly related to the issue but that function scares me. It's like when people ask for JSON.parse to be generic.

thepassle commented 1 year ago

Not directly related to the issue but that function scares me. It's like when people ask for JSON.parse to be generic.

Whatever, thats irrelevant, its just an example.

thepassle commented 1 year ago

Maybe a potential solution/proposal could be something like this?

function api<T>(endpoint: string): Promise<T> {
  return fetch(endpoint).then(res => res.json());
}

/**
 * @typedef {Object} Foo
 * @property {string} bar
 */

const r = await api/** @type {Foo} */('/api/foo');

// the type of `r` is `Foo`

This is still valid js, and its similar to how the generic would be provided in ts: api<Foo>('/api/foo')

KonnorRogers commented 1 year ago

This seems similar to this: https://github.com/microsoft/TypeScript/issues/27387

But also 👍

using Generic functions with JSDOC is quite painful.

thepassle commented 1 year ago

@RyanCavanaugh Would it be possible to get some feedback from the team on either this proposal or whats proposed in #27387?