Typescript: Suggestion: Add support for jsdoc-based templates with constrains

Created on 21 May 2018  路  3Comments  路  Source: microsoft/TypeScript

Search Terms

jsdoc template

Suggestion

This feature request is based on issue #1178.

1178 led to the implementation of @template and was closed afterwards.

The current implementation does not allow to add constrains for a generic:

add_support_for__template_jsdoc_ _issue__1178_ _microsoft_typescript

The latest statement from google in 2015 was that they might add it also to the closure-compiler some day:

generic_types_ _google_closure-compiler_wiki

Use Cases

For //ts-check projects it would be possible to use the full power of generics.

Examples

playground_ _typescript

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)

Stackoverflow: Is it possible to constrain a generic type defined in a jsDoc @template declaration? (May 2017)

JSDoc Fixed Suggestion

Most helpful comment

I think this should be:

/**
 * @template T {number}
 * @param a {T}
 */
function foo(a) { }

All 3 comments

I think this should be:

/**
 * @template T {number}
 * @param a {T}
 */
function foo(a) { }

Definitely would be helpful. Right now we're using /** @type {...} */ to use bounded generics in js (either defined inline or in an external d.ts file), but that has some serious drawbacks at the moment.

e.g. @type doesn't work on class methods, so we end up assigning the function to the prototype outside of the class body. It's also limited in scope to what's being immediately typed, unlike @template/generics in actual TS, so you can't really apply the type parameters across a whole class, for instance.

Readability is also not a small concern (all crammed into that @type comment :), and being able to declare as regular @params, etc jsdoc tags would be fantastic.

Compatibility with future Closure support isn't super important to us, at least, as we use enough TS-specific features (typeof, indexed access) that we have to do a cleaning pass on the code before passing to Closure anyways. If the solution is reasonable (like the above suggestion), there's also no reason Closure can't adopt it anyways.

24600 has this change.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhuravlikjb picture zhuravlikjb  路  3Comments

wmaurer picture wmaurer  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

uber5001 picture uber5001  路  3Comments

blendsdk picture blendsdk  路  3Comments