Defining a generic type for a value in JSDoc

Currently, I am working on a project where I utilize JSDoc for type annotations and typescript definition files to simplify the creation of those types. As part of this process, I am transitioning some generic types from JSDoc to typescript due to its ease of use.

One issue I encountered was when trying to directly assign a generic type to a variable, which resulted in an error prompting me to provide type arguments. For example:

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

This failed because WithDb requires two arguments, even though my intention was to indicate that it is a generic function. Fortunately, JSDoc allows for defining generic types using the @template syntax, allowing me to re-annotate the function like so:

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

Another variant could be:

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

However, this approach involves quite a bit of repetitive code that I would prefer to avoid. Is there an alternative method to bind the types other than using @type ?

Answer №1

Unfortunately, you're tied to using @type. However, there is a workaround that can help tidy things up a bit:

  1. To start, define a @typedef near the top of your file to create an alias:
/**
* @template T,K
* @typedef {import('./api').WithDb<T,K>} WithDb
*/
  1. Next, utilize your newly aliased type in your implementation:
/** @type {WithDb} */
const withDb = handler => async args => {

It may feel a bit cumbersome, especially if you have WithDb in your typings file. However, this approach can be beneficial if you use that type frequently, as it can save you some characters. While JSDoc offers versatility, it tends to be quite verbose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...

What is the step-by-step process for incorporating the `module` module into a Vue project?

ERROR Compilation failed with 6 errors 16:20:36 This specific dependency could not be located: * module in ./node_modules/@eslint/ ...

How to set up scroll restoration for the Angular Standalone Router?

The Angular Router provides the option to restore scrolling functionality, with documentation on how to implement it when loading data. Is there a way to configure the standalone router to automatically scroll back to the top of the router outlet? A demo ...

Is it possible to create a nested object inside of an array?

Looking to accomplish the following: let listOne: any = ['item1', 'item2', 'item3']; let details: any; // Previously, I had a loop running and 'row' was the response outputting items // in the listOne array const ...

The input type 'unknown' cannot be assigned to the output type 'string' when utilizing the filter(Boolean) operator

.ts: siteName: string; this.store.pipe( select(getSiteName), filter(Boolean), take(1) ).subscribe(siteName => this.siteName = siteName); Error: Type 'unknown' is not assignable to type 'string ...

Issue encountered while attempting to upload a document in Angular due to Content-Disposition

I am having trouble uploading a file using Angular. Every time I make the request, an error occurs stating: "Request has been blocked by CORS policy: Request header field content-disposition is not allowed by Access-Control-Allow-Headers in preflight respo ...

Using React-Bootstrap with TypeScript in your project

I'm currently working on creating a navigation bar using react-bootstrap. I've already installed the node-module as follows: "@types/react-bootstrap": "^0.32.11",. However, when I try to use it in my hello.tsx component, I encounter a compile err ...

The imported symbol from the typescript library cannot be found

Currently, I am in the process of developing a React/Redux application using Typescript. My goal is to streamline development by creating libraries for each unique "domain" or "feature" that will contain domain-specific details and provide an API to the ma ...

Cypress encountered an error: Module '../../webpack.config.js' could not be located

Every time I attempt to run cypress, an error pops up once the window launches stating "Error: Cannot find module '../../webpack.config.js'" Within my plugins>index.js file, I have the following in module.exports webpackOptions: require(&apos ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Error: The property referenced in the Typescript Ref of another Ref does not exist on the specified type

Utilizing the library https://github.com/lhz516/react-h5-audio-player, I am facing a challenge in correctly defining the type for my useRef without resorting to useRef<any>(null). I have managed to access and modify the audio element using the code ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

[innerText]: Text containing opening angle bracket

Can anyone explain why Angular [innerHtml] is removing text that comes after the left angle bracket? I encountered an issue with a line of HTML content, like so: text1 <text2 <a>link</a> Instead of displaying the content as is, it shows: ...

Is there a way to determine when an animation finishes in Vue Nativescript?

Vue Nativescript does not support the v-on hook, even though I found a solution for VueJS. Check out the solution here Currently, I am applying a class to trigger an animation: Template <Image ref="Image" :class="{scaleOut: scaleOutIsActive}" ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Ensure that parameters are validated correctly in the Next.JS application router using the searchParams method

When building the page, I need to properly validate params in the Next.JS app router using searchParams. My goal is to show a main image (coverImage) for each photo on the /gallery page. When a photo is clicked, I want to display more photos of the same k ...

I have successfully set up micro-cors on my system, and as I tried to compile, I received the following outcome

While working on the Next.js Stripe project, I ran into an unexpected problem that I need help with. ./src/pages/api/webhooks.ts:3:18 Type error: Could not find a declaration file for module 'micro-cors'. 'E:/Project/longlifecoin/node_module ...

Angular2 has encountered a malfunction with the chart feature

My attempt to create a Bar Chart with this GitHub repository is not working in Chrome. You can view my code on Plunker. Can someone help me identify the issue? Below is the updated code: app.ts import {Component, Pipe, PipeTransform} from 'angular2 ...

Angular object contains an unidentified property

While trying to send an object to the backend, I encountered an UnrecognizedPropertyException. Upon inspecting the object on both the frontend and backend, they appear to be identical. However, upon checking the object in the frontend console, I discovere ...