Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class

/**
 * @element my-element
 */
export class MyElement extends HTMLElement {
  publicMethod() {}
  /** @private */
  privateMethod() {}
}

customElements.define('my-element', MyElement);

along with a declaration file that has been generated using declaration and allowJs:

export class MyElement extends HTMLElement {
  publicMethod(): void;
  /** @private */
  privateMethod(): void
}

In addition, as part of a post-build script, this is concatenated to the declaration file:

declare global { interface HTMLElementTagNameMap { 'my-element': MyElement; } }

Now, when utilizing this element in a TypeScript file, accessing privateMethod is available in autocomplete.

import 'my-element'
const me = document.createElement("my-element")
me.// autocompletes `privateMethod`

The question arises on how to direct tsc to designate any methods, fields, or properties marked with the @private JSDoc tag as private?

Answer №1

As stated in the JSDoc documentation, the correct syntax for marking a private field is `/** @private */`, however, TypeScript does not handle it this way. To work with private fields in TypeScript, you need to use TypeScript's specific syntax and cannot rely on JSDoc alone.

Starting from TypeScript 3.8, ES6 style private fields are supported. You can indicate a private field by using the `#` symbol at the beginning of your method like this:

class Animal {
  #name: string;
  constructor(theName: string) {
    this.#name = theName;
  }
}

// example

new Animal("Cat").#name;
Property '#name' is not accessible outside class 'Animal' because it has a private identifier.

Alternatively, TypeScript also allows you to designate a field as private by using the `private` keyword, which will achieve the desired outcome. By doing this, the `privateMethod` will not be displayed during autocompletion (at least, it doesn't for me).

/**
 * @element my-element
 */
class MyElement extends HTMLElement {
  publicMethod() {}
  /** @private */
  private privateMethod() {}
}

let element = new MyElement()

element.privateMethod()
// Error: Property 'privateMethod' is private and only accessible within class 'MyElement'.

Here is an example demonstrating how this works with VS Code intellisense.

https://i.stack.imgur.com/kNoUb.gif

Answer №2

Ensure you have the correct version of TypeScript installed. Version 3.8 introduced support for this feature, so using Typescript 3.8 or newer should enable the @private JSDoc modifier.

To check the version of your TypeScript compiler, you can use the command tsc -h.

Answer №3

To exclude certain methods and classes from documentation, you should use the @ignore annotation.

When you add the @ignore tag to a symbol in your code, it will not be included in the documentation.

/**
 * @class
 * @ignore
 */
function Shoes() {
    /** The shoes' size. */
    this.size = null;
}

/**
 * @namespace
 * @ignore
 */
var Accessories = {
    /**
     * @class
     * @ignore
     */
    Wallet: function() {
        /** The wallet's color. */
        this.color = null;
    }
};

For more information, visit:

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

Learn how to configure your Angular uib-typeahead to display suggestions as soon as the model is bound

Currently, I am setting up a search functionality. Whenever a user inputs a character into the search box, I use the ng-change event to call an API, retrieve the model, and bind it to uib-typeahead. My goal is for uib-typehead to immediately start suggesti ...

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the n ...

Data transmission is only possible when the connection is in the 'Connected' state

Trying to set up a simple connection using SignalR in Angular 6, I wrote the following code: signalR.helper.ts public static setupHub<T>(hubUrl: string, eventName: string, callback: (data: T) => void, ...params: SignalRParam[]): HubConnection ...

Firefox does not support the event

// This function makes rows draggable within a table by utilizing mouse events. // It handles the drag initiation, movement, and stopping of the drag operation. makeRowsDraggable: function() { var dragInitiated = false; var startPageX, startPageY ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

Saving a complicated schema in Node using Mongoose fails to save or update when encountering an error

Greetings, I am facing challenges while trying to save a complex schema in MongoDB. const itemsSchema =new Schema({ cat: {type: String, required: true}, catItems: [{ items:{type: String}, isActive: {type: Boolean, default: true} }] }) ...

The offline functionality of the Angular Progressive Web App(PWA) is experiencing difficulties

As per the official guidelines, I attempted to create a PWA that functions in offline mode using pure PWA without angular-cli. However, despite following the official instructions, I was unable to make it work offline. The document in question can be foun ...

Utilizing Angular 2 to retrieve and assign object properties provided by a service to a local variable within a

My video service: public getExercise(exerciseId): Observable<Exercise[]>{ let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers, withCredentials: t ...

Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON(). Currently, I have instances of these classes represent ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

Using JavaScript to dynamically write content to the document in the

What is the correct way to write the HTML break tag "<br>" in JavaScript without it causing a line break? I want the tag to be displayed as text. For example, "the break tag in html is ..." See below for an example of what I am looking for. <scr ...

How can I trigger a method after the user has finished selecting items in a v-autocomplete with multiple selection using Vuetify?

After multiple selections are made in a v-autocomplete, I need to trigger a method. However, the @input and @change events fire after each selection, not after the full batch of selections. Is there an event that triggers when the dropdown menu closes? Al ...

Using a package with `webfontloader` in NextJs for Server-Side Rendering: A guide

Currently, I am working on creating an application with nextJS and incorporating a package that utilizes Webfontloader internally. After installing the library, my application encountered an error preventing it from running successfully. It seems like th ...

Incorporating HTML into the Ajax Response

I recently encountered a strange issue with a service that returns an HTML page as the AJAX response. This page contains a form that is automatically triggered by scripts within the page, resulting in a POST request being sent when the page is rendered. My ...