JSDoc assign generic type to a value

Viewed 162

I have a project where I'm using JSDoc to annotate types and typescript definition files to create those types more comfortably. I am porting some generic types from JSDoc to typescript, because it is easier to write. I found that I can not assign a generic type directly to a variable because it says that I must provide the type arguments. So, if I try to do this:

/*
 * @type {import('./api').WithDb}
 */
const withDb = handler => async args => {

It fails because WithDb requires two arguments, but this is exactly what I want, to say that this is a generic function. JSDoc allows you to define generic types using the @template syntax so I can re-annotate the function like this:

 /*
 * @template T
 * @template K
 * @type {import('./api').WithDb<T,K>}
 */
const withDb = handler => async args => {

OR

 /*
 * @template T,K
 * @type {import('./api').WithDb<T,K>}
 */
const withDb = handler => async args => {

But it is a lot of boilerplate that I would like to avoid. Is it any other way to bind the types other than @type ?

1 Answers

You're stuck using @type I'm afraid. But you can sort of clean it up by sweeping the boilerplate under the rug:

  1. Somewhere near the top of your file you can define a @typedef which will be an alias:
/**
* @template T,K
* @typedef {import('./api').WithDb<T,K>} WithDb
*/
  1. Then your implementation can use your newly aliased type:
/** @type {WithDb} */
const withDb = handler => async args => {

A bit clunky especially since you'll likely have WithDb in the typings file. but if you are using that type in a lot of places, then this will save you some characters. JSDoc covers a wide range of use cases, but it will always be pretty verbose.

Related