What is the method to utilize @template in JSDoc function in order to establish consistency between parameter and return types?

When working on an ecmascript project, I make use of @ts-check and a ts linter to follow TypeScript's formalism without actually using TypeScript itself.

Everything is running smoothly except for one issue: I am trying to implement JSDoc generics declaration to have the return type dependent on or inferred from a parameter type:

/**
 * @template V - Type de valeurs de la map.
 * @param {Map<string, V>} map
 * @returns {Object.<string, V>}
 */
function objectifyMap(map) {
    /** @type {Object.<string,V>} */
    const result = {};
    map.forEach((value, key) => { result[key] = value; });
    return result;
}

/**
 * @template V
 * @param {Object.<string, V>} object
 * @returns {Map<string, V>}
 */
function mappifyObject(object) {
    /** @type {Map<string,V>} */
    const result = new Map();
    Object.entries(object).forEach(([key, value]) => { result.set(key, value); });
    return result;
}

/** @type {Object.<string, string>} */
const obj = {};

/** @type {Map<string, string>} */
let map;
map = mappifyObject(obj);

However, I encounter an error with the obj parameter on the last line according to the ts linter:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type '{ [x: string]: V; }'.
  Index signatures are incompatible.
    Type 'string' is not assignable to type 'V'.
      'V' could be instantiated with an arbitrary type which could be unrelated to 'string'.ts(2345)

I suspect that the ts linter expects something like

map = mappifyObject<string>(obj);
but since I'm only utilizing @ts-check and not the full TypeScript compiler, I cannot do that directly.

Is there any workaround for this situation?

Answer №1

I'm not too familiar with the syntax you're using for the Object.<K, V> type. In TypeScript, you would typically see either {[x: string]: V} or Record<string, V> used for typing. Both of those options are valid for me:

/**
 * @template V
 * @param {{[x: string]: V}} obj
 * @returns {Map<string, V>}
 */
function convertToObject(obj) {
    /** @type {Map<string,V>} */
    const result = new Map();
    Object.entries(obj).forEach(([key, value]) => { result.set(key, value); });
    return result;
}

/** @type {{[x: string]: string}} */
const object = {};

/** @type {Map<string, string>} */
let map;
map = convertToObject(object);

or

/**
 * @template V
 * @param {Record<string, V>} obj
 * @returns {Map<string, V>}
 */
function toObject(obj) {
    /** @type {Map<string,V>} */
    const result = new Map();
    Object.entries(obj).forEach(([key, value]) => { result.set(key, value); });
    return result;
}

/** @type {Record<string, string>} */
const object = {};

/** @type {Map<string, string>} */
let anotherMap;
anotherMap = toObject(object);

Both options should work without any errors.

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

Locate the item within an array that contains the most keys

Can you help me with a coding challenge? I have an array of objects set up like this: let items = [ { a: '', b: 2, c: 3 }, { a: '', b: '', c: 5, d: 10 }, ...

Retrieve information from an API and assign the corresponding data points to the graph using Material UI and React

I have 4 different APIs that I need to interact with in order to fetch specific details and visualize them on a bar graph. The data should be organized based on the name, where the x-axis represents the names and the y-axis represents the details (with 4 b ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Creating Vue Components in PHP with no need for Webpack or Bundlers

Our company is currently in the process of incorporating Vue into our workflow, but we are facing challenges due to the lack of Javascript Build tools like Webpack. This means we cannot use Babel or Template Literals (`), making it difficult to define Comp ...

What could be causing my Angular JS application to malfunction?

Presenting myFirstAngularApp.html <html ng-app="store"><!-- The "ng-app" attribute initializes an Angular app. Everything inside this tag is considered part of the Angular app due to ng-app --> <head> <link rel="stylesheet" type= ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

A Typescript generic that creates a set of builder function interfaces

Consider a Typescript interface: interface Product { url: URL; available: boolean; price: number; } We need to create a generic type that can produce a builder type based on any given interface: interface ProductSteps { url: (data: unknown) => ...

Testing the timestamp field rule in security rules for Firestore

I have been creating unit tests for my firestore security rules with the help of the node.js library @firebase/rules-unit-testing Here is the security rule I have set for updating a document: allow update: if request.auth.uid != null && request. ...

What causes the error "searchInput" to be undefined?

Currently, I am facing an issue while attempting to search for individuals stored in an array within the Redux store. Whenever I try to execute a search, an error is triggered with the following message: Cannot read property 'searchInput' of und ...

Combining arrays of objects in JavaScript

I am currently working on combining different arrays: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...arr ...

What is the best way to have Protractor pause until a specific promise is resolved?

I am having an issue with my website where clicking a button triggers an angular service that returns some data to be displayed on the page. I need to write an angular test that clicks the button, waits for the promise to resolve, and verifies that the dat ...

Displaying a DIV inside an embedded DIV when selecting an option in HTML by utilizing JavaScript

My goal is to create a page where users initiate a questionnaire by clicking START in a web form - this action will open the DIV for the first question. As users answer each question (with yes/no choices), it will either display a specific DIV related to ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Sending Information from Node/Express to Client-Side JavaScript

I'm a bit confused about how to make this work, and my searches have not yielded the answer I need. Currently, I have been successfully passing data from a node and express server to my front end ejs. Now, I am attempting to integrate charts.js into m ...

What is the best way to accurately determine an element's location after scrolling to it?

I'm currently working on pinpointing the location of a specific element on a webpage once it has been scrolled to using JavaScript. Queries: How can I precisely determine the position of an element post-scroll? What are some common errors or extra st ...

Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service. One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

Event object not being passed to function in UIWebView Javascript onclick event

When inserting HTML dynamically using simple NSStrings and then loading it into a UIWebview, the following approach is taken: [NSString stringWithFormat:@"<div onclick=\"MyClickEvent(e);\"....some more text here"> A function is defined li ...

Encountered an error: Object(...) function not defined when using React, Formik, and Webpack

I have encountered an issue while trying to use both Formik and React-Form-Hooks in my project. Despite using Typescript as my language and Babel as the transpiler, both libraries throw the same error when compiled. Uncaught TypeError: Object(...) is not ...