How can I define the parameter for a function that has been passed in typescript using generics?

When looking at the code below in the resHandler() function, it seems that res is of type 'any'. However, I explicitly specified the type when calling the sendRequest() function. Shouldn't res automatically be of type 'PersonType'?

type PersonType = {
    name: string;
    age: number;
}
async function sendRequest<T>(resFn: (data: T)=> void){
  const res = await fetch('some-url');
  let data: T = await res.json();
  resFn(data);
}

sendRequest<PersonType>(resHandler)

function resHandler(res){
  console.log(res)
}

Thank you for your assistance.

Is there a way for the res parameter in the resHandler() function to automatically match the assigned data type from the sendRequest() function?

Answer №1

Is there a way to automatically determine the type of the 'res' in resHandler?

Unfortunately, you cannot do that.

In Typescript, the type of a value is not determined based on how it is used.

Instead, Typescript verifies if the usage of a value aligns with how its type was declared.

Consider this scenario:

sendRequest<PersonType>(resHandler)

const someResponse: SomeOtherType = getJson('...')
resHandler(someResponse) // What should be the type of the argument here?

Would you expect the type of the resHandler argument to change to res: PersonType | SomeOtherType? Typescript does not make that change.


Typescript first looks at this:

function resHandler(res){
  console.log(res)
}

If no type is provided for res, Typescript infers it as any (which could be an issue if noImplicitAny is enabled).

Then it checks to ensure that everywhere the resHandler function is used is compatible with its interface.


To avoid manually typing the res parameter, you can inline the function like this:

sendRequest<PersonType>((res) => console.log(res.name)) // valid

In this case, the usage is tied to the declaration because the function is created within the context of T extends PersonType, so Typescript knows that typeof res extends PersonType.

Alternatively, you can manually type the argument if you want direct interaction with PersonType.

function resHandlerForPerson(res: PersonType){
  console.log(res.name)
}

sendRequest<PersonType>(resHandlerForPerson) // valid
sendRequest<{ someOtherType: string }>(resHandlerForPerson) // type error

Now you have a resHandlerForPerson function specifically for PersonType, which will result in a type error if used with any other type.

See Playground

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

Tips for sorting data based on duplicate dates within a single array element

Here is the existing Object Array structure: [ { "date":"12-09-2019 12:00 PM", "id":"1", "name":"hello1" }, { "date":"12-09-2019 03:00 PM", "id":"2", "name":"hello2" }, { "date":"12- ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Angular - ng-repeat failing to update when nested array is modified

Utilizing ng-repeat to render data fetched via a GET request that returns an array. HTML <div ng-controller="candidateCtrl" > <div class="table-responsive"> <table class="table table-striped"> <thead> ...

The value returned by a component should remain consistent regardless of where it is invoked. Additionally, the main component in React should not re-render when the state of a sub-component is

I am looking to have the same value displayed in the Home function from the Component, without causing a rerender when the useState in Component is updated. import { useState, useEffect } from "react"; function Component() { const [count, setC ...

Unable to exclude folder while creating production build is not functioning as intended

I've got a directory full of simulated data in the "src/api/mock" folder, complete with ts and JSON files. I'm attempting to have Webpack skip over them during the production build process. I attempted to implement the following rule, but unfortu ...

Interface key error caused by the TypeScript template literal

Version 4.4.3 of Typescript Demo Playground Example -- interface IDocument { [added_: `added_${string}`]: number[] | undefined; } const id = 'id'; const document: IDocument = { [`added_${id}`]: [1970] } My Attempts: I made sure that id in ...

Establish a connection to an SSH server using Node.js code, specifying the SSH key and server hostname for

Having VPN access allows me to SSH into the server using the following command in the terminal: ssh qa-trinath01.my-qa This command works perfectly fine when executed from the terminal. However, when attempting to connect via Node.js, I encounter issues ...

"Exploring the concept of undefined within object-oriented programming and its role in

Recently diving into Express and trying out routing by creating an object in a file to export. import userController from "../controllers/userController.js" // get all users router.get("/", isAuth, isAdmin, userController.list) Encoun ...

Prevent page refresh after unsuccessful validation

I have successfully implemented JavaScript validation to ensure that the form cannot be submitted without at least one checkbox being selected. A message is displayed to remind the user to select at least one option. Now, I am facing an issue where the fo ...

How to effectively secure disabled or read-only input fields from JavaScript?

I am currently working on creating an HTML/PHP page that includes three hidden input fields. These fields are pre-set with values by the server and have the disabled attribute applied to them. The purpose of these hidden fields is to store information on o ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Using TypeScript with generic parameters allows for flexibility while still being able to verify if a specific property is present

I am in the process of gradually converting a large SvelteKit application to TypeScript, focusing on refining the API layer. Currently, I am grappling with a function that has two generics: // Function that either performs a POST or a PUT export function s ...

Apply a border to the div that has been selected

I have a tool for storing information and I am using *ngFor to display each instance in a line. Is there a way to add a border when clicking on a line? The border should only appear on the clicked line, disappearing from the previous one if another line i ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

Is it possible to use an ngClick function in one directive to toggle data in another?

Currently, I am in the process of developing a weather application using Angular 1.5.8 where users should have the option to switch between imperial and metric units for temperature and wind speed. The toggle feature along with all the weather data fetche ...

The functionality of express types is not optimized in the TypeScript playground

Have you attempted creating a demo for the TS type of express? Follow the Type Acquisition guide of TS Playground to manage the imported types by using // types: npm_tag_or_version. Despite specifying both versions, none seem to be functioning correctly. ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

When passing e: EventTarget as a forwarded prop through a wrapper component, Typescript raises an error about the missing "value" property in the onChange function

In my project, there is a custom component called SelectField that serves as a wrapper for rendering label, helper text, and select input (inspired by TextField from @material-UI). The SelectField component exposes props like value and onChange, which are ...