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

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser. While I successfully retrieve all products using the following code: export async function getAllProducts() { const productData = await client.fe ...

Toggling multiple ions simultaneously does not function independently

I encountered a problem while working on an ionic app. I needed to have individual control over toggle switches, but my current code toggles all switches at once whenever one switch is tapped. Is there a way to fix this and manage each toggle switch separa ...

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Basic JavaScript string calculator

I'm in the process of creating a basic JavaScript calculator that prompts the user to input their name and then displays a number based on the input. Each letter in the string will correspond to a value, such as a=1 and b=2. For example, if the user e ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Animating multiple elements in Angular 2 using a single function

Currently, I am delving into Angular and faced a challenge while attempting to create a toggle categories menu. Within my navbar component, I have an animation trigger set up as follows: trigger('slideCategory', [ state('opened&apo ...

Unable to establish a hyperlink to specific section of page using MUI 5 Drawer

When attempting to link to a specific part of my first page upon clicking the Shop button in the navigation Drawer, nothing happens: https://i.stack.imgur.com/FUQCp.png This snippet shows the code for the MUI 5 Drawer component: <Drawer anch ...

Ensuring validity using dynamic context objects within Joi

I need to implement a dynamic validation system that involves downloading an object at runtime and saving it as a well-formed .json file. The objective is to use the values from this downloaded object as part of a validation process using Joi.validate wi ...

HTMLMediaElement does not have the setSinkId method

I am currently in the process of developing a WebRTC application using Angular, with the goal of managing audio output through the setSinkId() method within HTMLMediaElement. However, when attempting to use this method, I am encountering an error message s ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

How can one discern the most effective method to identify JavaScript code that alters particular HTML content on a webpage?

On my website, I have a <p> tag and I am interested in knowing which JavaScript function is responsible for adding text inside this element. Is there a special method in Chrome to add a listener on this tag and pinpoint the script that writes to it ...

React - Updating the Color of a Specific Div within a Map Component

Currently, I am delving into React and Material UI and facing an issue with changing the background color of a clicked div. As it stands, all the divs are being affected when one is clicked. My goal is to have the background color transition from white to ...

When utilizing :id with Vue, HTML attributes become hidden from view

I am facing an issue where I need to make HTML elements visible, but they appear invisible upon rendering. Below is my HTML code: <div class="created-links-wrapper" v-for="item in createdUrls" :key="item._id"> <d ...

The concept of setTimeout and how it affects binding in JavaScript

I have limited experience with jquery, mainly using it for toggling classes. However, I will do my best to explain my issue clearly. I have three div elements and when one is clicked, the other two should rotate 90 degrees and then collapse to a height of ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...

Don't forget to retain the checkboxes that were chosen in the

I am looking for a solution to a specific scenario. When I open a modal box and check some checkboxes, I want those same checkboxes to be selected the next time I open it. Below is an example of my code. Main Controller modal function function openModa ...

development of MapLayers with rails and javascript

As a newcomer to RoR, I am encountering an issue that seems to be eluding me. I attempted to replicate the example application found on the mapLayers GitHub repository at https://github.com/pka/map_layers/wiki. However, all I see is the JavaScript code gen ...