Having trouble providing JSDoc annotations for a generic identity function

My expectation was that the following code would work:

// @ts-check

/**
 * @template A
 * @callback Identity
 * @param {A} a
 * @returns A
 */

/**
 * @template A
 * @type {Identity<A>}
 */
const id = (a) => a

/**
 * @type {number}
 */
export const five = id(5);   // bang!

When calling id, I assumed that the generic type A would be applied to type number.

However, running tsc results in the following errors:

error TS2322: Type 'A' is not assignable to type 'number'.
error TS2345: Argument of type 'number' is not assignable to parameter of type 'A'.
  'A' could be instantiated with an arbitrary type which could be unrelated to 'number'.

Answer №1

It seems that the issue with the provided code not working is due to the JSDoc @template tag only affecting the type of the function's parameters and return value, not the function itself. In this case, the function id is defined as a generic function without actually passing any generic type parameters. As a result, the type of id defaults to (a: any) => any, causing TypeScript to struggle with inferring the correct types when calling id(5).

To resolve this, you should pass a generic type parameter to id when calling it. For example:

const five = id<number>(5);

This informs TypeScript that the type of the parameter when calling id is number, enabling it to deduce that 'five' should also be of type number.

Below is the revised code that functions correctly:

// @ts-check

/**
 * @template A
 * @callback Identity
 * @param {A} a
 * @returns A
 */

/**
 * @template A
 */
const id = <A>(a: A) => a;

/**
 * @type {number}
 */
export const five = id<number>(5);

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

Calling synchronous methods in Typescript

Hello Nativescript Team, I seem to be stuck with making method calls in my code. Could you please provide me with guidance on how to implement synchronous method calling in Nativescript + Angular? import { Component, OnInit, AfterContentInit } from " ...

The interpolation error in Angular is causing an undefined result to occur

I am currently facing an interpolation issue that involves working with data from an API in the following format: {columna1=6.022, columna2=0.0, columna3=3.14.....,columnaN=5.55 } There are instances where there is only one 'columna', while in s ...

What is the correct way to fetch all attributes of a particular key type from an interface using TypeScript?

Exploring arrays, I discovered the following setup: const MyArray = [ { name: "Alice", age: 15 }, { name: "Bob", age: 23 }, { name: "Eve", age: 38 }, ]; type Person = typeof MyArray[number]; Curious, I attempted a sim ...

Troubleshooting: Unable to locate .vue.d.ts file during declaration generation with Vue, webpack, and TypeScript

Currently, I am developing a library using Typescript and VueJS with webpack for handling the build process. One of the challenges I'm facing is related to the generation of TypeScript declaration files (.d.ts). In my source code, I have Typescript ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

Importing ES6 modules in TypeScript using absolute paths

I've been on a quest for hours trying to figure out how to import local ES6 modules using an absolute path. Every time I attempt to import something in a module like : import { Module } from "src/my-module"; I keep getting the error "Error: Cannot f ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

Error encountered while defining properties for React Three's Text component in react-three/drei [TypeScript compilation error]

The Challenge Overview In my quest to develop a VR web application using React Three and XR libraries, I have encountered a TypeScript error during the build process. The issue seems to revolve around missing properties while constructing the Text compone ...

Adding dynamic values to nested form groups in Angular Form Array

After following a tutorial on creating a reactive form in an Angular application, I managed to implement it successfully. However, I encountered an issue when trying to add an additional control called "setNumber" to the form array. I want this control to ...

Encountering a Typescript compatibility problem during the transition to Angular 12

I keep encountering this recurring error message: - Generating browser application bundles (phase: setup)... An error occurred during the build: Error: The Angular Compiler requires TypeScript >=4.2.3 and <4.4.0 but 4.5.4 was found instead. at ch ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

Why did the developers of Angular 2+ choose to use JavaScript Objects instead of Typescript Classes for defining Router routes?

When working with the Angular 2+ Router, the standard approach involves defining routes in the app-routing module. app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

What is the best way to emphasize when the path matches exactly with '/'?

Is there a way to highlight the path only when it exactly matches '/'? Currently, even on 'Page 2', the 'Home' link is still highlighted. Check out the plunker here .active { color: red; } <a routerLinkActive="active" r ...

In Ionic 2, any modifications made to the data model will only be reflected in the user interface after there is

Q) Why does my data seem to magically appear on the UI after interacting with it, even though I have made changes in the backend? For instance, when fetching and updating data bound to a list, such as: this._LocalStorageService.getClients().then( (data ...

Issue: "Exported functions in a 'use server' file must be async"

I'm currently working on implementing layout.tsx in the app directory of Next.js 13 to create a navigation layout that appears on all pages. I've successfully configured it so that the navbar updates when a user logs out or signs in, but there&ap ...

Tips for accessing the nested formArray value using a getter in Angular

I am currently attempting to retrieve form values using the getter method and then dynamically pushing them to update the form with values. However, I am faced with a nested array at the moment, which is causing issues with retrieving the form values. Bel ...

Trying to find a more efficient method to export multiple classes as an array in typescript

I've organized my files like this: index.ts folder/ a.ts b.ts subfolder/ c.ts d.ts e.ts ... In each file, there is one default exported class and I want index.ts to export all these classes as an array. Currently, I achieve thi ...