Using JSDoc, consider a Plain Old JavaScript Object (POJO) as an instance

When working with a class and a function that accepts an instance of that class or a similar POJO object, there is a desire to use JSDoc annotations.

class Example {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

/**
 * @param {Example} example
 */
function handleExample(example) {
    console.log(example.x, example.y);
}

// How can we indicate in JSDoc that both instances of Example and Example-like objects are valid arguments?
handleExample({
    x: 'this is x'
});

The use of @param {Example} example seems to be on the right track, but an error occurs when passing a POJO instead of an actual instance of Example.

Are there any clever JSDoc techniques to clarify that both a specific Example type and a similar Example-like object should be accepted?

Answer №1

Opt for employing a type union:

/**
 * @param {Test|{a,b}} test
 */
function handleTest(test) {
  console.log(test.a, test.b);
}

The part in |{a,b} of the type represents different acceptable types. In order for the IDE to acknowledge that a and b are anticipated properties, it's advised not to solely use {Test|{}}.

This serves as a more concise version; alternatively, you have the option to specify what constitutes "Test-like" objects if there is an intention to employ and document TestLike objects in multiple instances:

/**
 * @typedef {object} TestLike
 * @property {string} a - some property a
 * @property {string} b - some property b
 */

/**
 * @param {Test|TestLike} test
 */
handleTest(test) {
  // ...
}

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

Utilize a for loop within a query to showcase a modal popup

I have a specific requirement: I want to display a modal popup window based on a for loop using jQuery. I have attempted the following approach, where I want the modal popup to be displayed based on the value of a flag. For example, if the Flag value is 3, ...

Step-by-step guide on compressing a JavaScript array

What is the best way to compress an array? I am currently attempting to compress an array using the lz-string library and converting it to/from strings. However, I am encountering issues with decompression, as I am getting null, 0, or [] as the output. B ...

What causes getBoundingClientRect() in Javascript to occasionally produce decimal values?

Currently, I am experimenting with an HTML5 canvas element. A major concern of mine is setting up a mousemove event to monitor the movement of the mouse over the canvas for drawing and other purposes. Unfortunately, I have not been able to locate a definit ...

What is the best way to stop a jQuery function from applying titles extracted from the first row th's in thead's to multiple tables in a document?

My circumstances: I am new to jQuery and Stack Overflow, seeking assistance for my website project. The challenge: Building a website using Bootstrap 3.3.6 with intricate data tables that need to be stacked dynamically on mobile devices using CSS. It is c ...

Retrieving information from defined component in Vue

Recently, I've been diving into Vue and learning about templates. I discovered that you can pass data from a child component to a parent component using $emit(). app.js Vue.component('tweet-postbox', require('./components/tweetPos ...

Having trouble getting my javascript integration to work in a Django template - any ideas on what could be causing

As a newcomer to Django, I'm working on creating a small webpage that displays a chart using Chart.js. My goal is to load the JavaScript file statically. To achieve this, I have set up a basic HTML file named data_table.html and included a "static" fo ...

What is the best way to send a prop from a parent component to its child using context in React?

Currently, I am working on fetching data in a React application. My goal is to extract an individual value from the response and pass it as a prop in a context from a parent component. The `trendingData` variable holds information retrieved from an API cal ...

Modifying JavaScript Code in Inspect Element Editor

When I modify the HTML content using Chrome's Inspect Element editor, any changes made are immediately visible. However, when I make changes to the JavaScript code, the modifications do not take effect. For example, if I have a button that triggers a ...

What is the best way to retrieve a value from an asynchronous function in Node.js?

var fs = require('fs'); var ytdl = require('ytdl-core'); var favicon = require('serve-favicon'); var express = require('express'); var app = express(); app.use(favicon(__dirname + '/public/favicon.png')); ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

Spinning item using a randomized matrix in Three.js

I'm in the process of creating a 3D die using Three.js that will rotate randomly when clicked, but I'm struggling to update the axis values properly. Here's where I'm currently at: <style type="text/css" media="screen"> html, ...

Turn the image inside the div with the nth-child selector into a clickable link

I'm currently facing a challenge on my Squarespace website where I need to add individual links to various images using jQuery. The issue is that these images do not have a shared class, and unfortunately, I am limited to adding custom CSS or JavaScri ...

What is the process for generating a subpage within the main page without the need to navigate away from the primary

On my main page, I have a login button. Instead of redirecting the user to a new page, I want it to simply display a login box. You can see an example of this on medium.com when you click on 'sign in'. Is it possible to achieve this with only HTM ...

Strange behavior is observed when using ng-view inside ng-controller, especially when refreshing the

Here is the code I am working with: <body ng-controller="CoreCtrl"> <div ng-cloak> <!-- NavBar --> <div ng-include="'/app/core/navbar.html'"></div> <!-- Main content --> <div class="con ...

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

How can Mbox content be loaded dynamically according to the selected option in a dropdown menu, instead of loading it when

I am looking to enhance my asp.net page by adding a new MBox that will be triggered based on the dropdown selected value. Unlike other MBoxes on the page that load on page load, I want this new MBox to dynamically pass custom parameters to T&T when a val ...

Extracting Ajax data - iterating through each piece of information

I am facing an issue with my ajax code. I have a collection of checkboxes, where the goal is to insert the data from the selected checkboxes into the database. When I choose just one checkbox, the insertion works fine. However, if I select multiple checkb ...

Adjust the radius parameter in the Google Maps API

I'm attempting to adjust the radius of a circle on Google Maps API using the jquery-location-picker. Here's a simplified version of what I'm trying to achieve: $('#map').locationpicker({ location: { lat ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

Having trouble bringing in components to my pages in ReactJS

There seems to be an issue preventing me from importing the components onto the page, resulting in this error: ERROR in ./src/pages/Home.jsx 4:0-37 Module not found: Error: Can't resolve './components/Card' in '/home/c4p1/blog/src/pages ...