What is the proper way to reference a different TypeScript type within comments or JSDoc?

While I am well-versed in Javadoc, there is a feature that allows you to create links referring to the documentation of another type, as discussed here:

/**
 * some java thingy. see this other java thingy too {@link OtherThingy}
 */
public class Thingy { /*...*/ }

/**
 * some other java thingy. see the first java thingy too {@link Thingy}
 */
public class OtherThingy{ /*...*/ }

I am curious if TypeScript's version of JSDoc offers a similar functionality. While markdown and web links can be used in comments, they do not achieve the same result I am looking for.

If anyone has information on JSDoc or TypeScript documentation tools that can help with this, it would be greatly appreciated :)

Edit: Following the responses below, it appears that this feature is supported by JSDoc but may not be available in VSCode. Are there any valid syntax options in VSCode?

Answer №1

Absolutely, though results may vary.

1: Exploring the use of @link in Selenium-Webdriver's TypeScript typing file

/**
 * Converts a level name or value to a {@link logging.Level} value.
 * If the name/value is not recognized, {@link logging.Level.ALL}
 * will be returned.
 * @param {(number|string)} nameOrValue The log level name, or value, to
 *     convert .
 * @return {!logging.Level} The converted level.
 */
function getLevel(nameOrValue: string | number): Level;

2: Documentation on using @link in JSDoc

The examples below illustrate various ways to provide link text for the {@link} tag: Providing link text

/**
 * See {@link MyClass} and [MyClass's foo property]{@link MyClass#foo}.
 * Also, check out {@link http://www.google.com|Google} and
 * {@link https://github.com GitHub}.
 */
function myFunction() {}

By default, the example above generates output similar to this: Output for {@link} tags

See <a href="MyClass.html">MyClass</a> and <a 
href="MyClass.html#foo">MyClass's foo
property</a>. Also, check out <a 
href="http://www.google.com">Google</a> and
<a href="https://github.com">GitHub</a>.

Answer №2

Absolutely, the @link feature is fully functional

You have the capability to utilize {@link OtherThingy} in your documentation, and it has been operational within VS Code since the year 2021. Simply incorporate it for inline referencing.

Detailed information and additional choices

In addition to using the aforementioned approach, when dealing with VSCode version 1.52 (released in November 2020), you may also contemplate employing an alternative tag:

Preliminary support for JSDoc @see tags

The utilization of JSDoc @see tags facilitates references to various functions and classes within your JSDoc comments.

An illustration below illustrates a scenario where the crash function refers to the WrappedError class from a distinct file:

// @filename: somewhere.ts
export class WrappedError extends Error { ... }

// @filename: ace.ts
import { WrappedError } from './somewhere'

/**
* @see {WrappedError}
*/
function crash(kind) {
   throw new WrappedError(kind);
}

VS Code now encompasses rudimentary @see references during rename operations.

Furthermore, by executing go-to-definition on the @see tag's content, and incorporating @see tags within the list of references, enhanced support for these features is anticipated in forthcoming updates.

Mark points out in the discussions that:

JSDoc @link inclusion

We are pleased to announce the inclusion of JSDoc @link tags functionality within JavaScript and TypeScript comments.

These tags allow for the creation of interactive links to symbols within your documentation:

https://i.sstatic.net/RpXVp.gif

JSDoc @link tags adhere to the format: {@link symbolName}.

If desired, you can specify alternate text to display instead of the symbol name: {@link class.property Alt text}.

@link integration extends to hovers, suggestions, and signature assistance.
We have also updated vscode.d.ts to encompass @link elements.


Please note: cachius expresses insights in the remarks:

import { MyClassName } from "path/to/MyClassName";

If MyClassName remains unimported, including @see MyClassName within the JSDoc would merely exhibit any upon hover, without enabling ctrl + clickthrough functionality to declarations/usages.

By importing the type, this limitation is overcome, even if the sole occurrence exists within the JSDoc commentary.
This practice proves beneficial when modules/classes reference each other conceptually, albeit without direct usage.

Nevertheless, unused imports could trigger eslint alerts, which can be suppressed utilizing:

// eslint-disable-next-line @typescript-eslint/no-unused-vars 

Daniel Steigerwald supplements the discussion with insights in the comments

It is imperative that the imported type is actively utilized.
Failure to do so renders the JSDoc processing ineffective.

Moreover:

An additional critical issue arises when destructuring occurs, as any portion of JSDoc featuring @ is disregarded, consequently rendering it ineffectual. To mitigate such occurrences, all instances of @example need substitution with Markdown annotations, like ### Example ts ...


Eric Haynes adds further perspective in the responses:

Consider opting for the following approach:

import type { MyClassName } from 'path/to/MyClassName';  

Type imports undergo removal during compilation, unlike traditional imports within the compiled JavaScript.
(or

import { type MyClassName, OtherThing }
if another import already exists along that path)


Utilizing import { type Foo } appears to present a viable solution.
Nonetheless, despite the absence of the

typescript Foo is declared but its value is never read
warning, errors relating to no-unused-vars eslint pertaining to the import might persist.
Is there a workaround for this issue or does it signify an eslint anomaly?

Although TypeScript acknowledges the import's purpose for type delineation, thereby eliminating it in transpiled JavaScript, ESLint's default settings may not recognize type-only imports as "utilized". Consequently, such entities are tagged as unused variables by ESLint.

One potential resolution involves customizing the ESLint configuration to overlook unused vars solely imported for types. This can be achieved by adjusting the no-unused-vars rule within your .eslintrc setup, particularly leveraging the ignoreRestSiblings and argsIgnorePattern options to exclude type imports:

{
  "rules": {
    "no-unused-vars": ["error", { "ignoreRestSiblings": true, "argsIgnorePattern": "^_" }],
    "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
  }
}

This method mandates tweaking to pinpoint type imports while steering clear of inadvertently silencing genuinely unused variables.

An alternative route entails integrating the eslint-plugin-import plugin, offering refined control over linting matters associated with imports. This plugin introduces a rule named import/no-unused-modules, which allows configurations conducive to type-only imports. Implement the necessary adjustments within your .eslintrc after installing the plugin:

{
  "plugins": ["import"],
  "rules": {
    "import/no-unused-modules": [1, { "ignoreExports": ["path/to/your/typescript/files/**/*.ts"] }]
  }
}

You should define paths and matching patterns relevant to your project structure: although more upfront effort is required, accuracy in linting behavior management improves.

If the concern arises sporadically and global ESLint alterations seem unwarranted, consider deactivating the ESLint rule exclusively for specific imports:

// eslint-disable-next-line no-unused-vars
import { type Foo } from './foo';

In projects reliant on the @typescript-eslint plugin (highly recommended for TypeScript endeavors), leverage its augmented version of the no-unused-vars rule. Verify that your ESLint setup accesses this revised rule, rather than the conventional variant:

{
  "extends": [
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": {
    "no-unused-vars": "off", // Disable base ESLint edition
    "@typescript-eslint/no-unused-vars": ["error"] // Employ TypeScript ESLint interpretation
  }
}

The adapted rule demonstrates elevated proficiency in recognizing TypeScript-specific traits of type-only imports, thus averting redundant flags indicating their underuse.

Answer №3

When using VS Code, the {@link} syntax is treated as a comment and does not receive any special parsing. This means it is displayed exactly as inputted. An open issue has been identified to address this behavior, which you can find more information about here.

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

How can one effectively utilize TypeScript with native JavaScript methods and calls?

After a long break from TypeScript, I am struggling to override implementations or use native methods in the .ts file. The ones highlighted in red, excluding this, are causing errors. https://i.sstatic.net/WhcRM.png I'm not getting autocomplete sup ...

What is the correct method to set the root path following a logout?

Just starting out with Ionic and working on creating a login and logout process. Here is the structure: Login: LoginPage => TabsPage Logout: TabsPage => LoginPage Currently, I am handling logging out using this.navCtrl.setRoot(LoginPage). While ...

Is OnPush Change Detection failing to detect state changes?

Curious about the issue with the OnPush change detection strategy not functioning properly in this demonstration. My understanding is that OnPush change detection should activate when a property reference changes. To ensure this, a new array must be set e ...

Exploring Opencascade.js: Uncovering the Real Text within a TCollection_ExtendedString

I am currently attempting to retrieve the name of an assembly part that I have extracted from a .step file. My method is inspired by a blog post found at , however, I am implementing it using javascript. I have managed to extract the TDataStd_Name attribut ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

Is it possible to achieve efficient Autocompletion features within VS Code?

Just had my first experience with PhpStorm and I must say, I'm impressed, especially with the completion feature. Pressing Ctrl + Space on my Mac gives me relevant suggestions, like when I'm in a JS file and my project includes jQuery, I get Ele ...

Is there a more efficient approach to creating a Typescript XML parser that does not rely on PropTypes?

I'm currently designing the architecture for a web application that will require the consumption of SOAP APIs in hundreds, if not thousands, of instances. These implementations will be developed by 200-300 different developers over a span of several y ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

Using NPM packages for managing dependencies with IOC containers

At our company, we utilize internal SDKs which sometimes require the use of Inversify. However, I've noticed that managing multiple IOC containers across different packages can become quite challenging. For example, when one package depends on another ...

Arranging a group of objects in Angular2

I am facing challenges with organizing an array of objects in Angular2. The structure of the object is as follows: [ { "name": "t10", "ts": 1476778297100, "value": "32.339264", "xid": "DP_049908" }, { "name": "t17", "ts": 14 ...

What is the best way to tally up the letters within a table?

Currently, I am working on a task to count letters and display them in a table. The existing table is functional but has too many rows and incorrect counts. A 2 ...

Uploading images using Angular and PHP: A comprehensive guide

I am a beginner in Angular and I am having trouble uploading an image from Angular as I encounter 4 errors: 1) Error in the post method: Cannot find name 'formData'. Did you mean 'FormData'?ts(2552) 2) Error in the subscribe method: ...

Converting an Observable containing an Array of StaffInterface objects to a plain Array of StaffInterface objects in @ngrx/store select

Trying to retrieve an Array<StaffInterface> from an Observable<Array<StaffInterface>> in ngrx store.select. The store.select method returns the Observable<Array<StaffInterface>>, which I then need to convert into an Array<S ...

Context for Apollo server has not been defined

Following the upgrade to Apollo v4 and migration guide, my project was functioning properly. However, the context is now undefined. const { url } = await startStandaloneServer(server, { listen: { port: 3000 }, context: async ({ req }) => { try ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Customizing the standard ping protocol for native JavaScript websockets

In my Expo (React Native) project, I am working on implementing a protocol to manage stale websocket connections on both the client and server sides. The 'ws' package offers built-in callback handling for the 'pong' event (and sending p ...

What is the method for filtering out specific fields in a template string?

I am currently working on defining constraints for the method field type event = { [k: `on${string}`]:(e:string)=>void } However, I need the event argument to be a number for fields that do not begin with 'on' type event = { [k: ` ...

How to navigate to a custom error page in Angular 2

I have set up a custom error handler and in that, I want to redirect to a custom error page displaying the message "sorry, an error occurred......". To achieve this, I added a route in my app-routing.module.ts file as follows: import { NgModule } from &a ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...