How can we specify the type based on the argument type of a callback function in Typescript?

How can I specify the parameter type for the callback function handle?

const util = (handle: (p) => string) => ({
  // I expect the log function's parameter [p] type to come from the handle function's parameter type
  log: (p: Parameters<typeof handle>[0]) => console.log(handle(p))
});

// Currently, the log function parameter is recognized as type 'any' instead of 'string'
const { log } = util((a: string) => String(a));

// Expect log function parameter to be string

const { log } = util((a: string) => String(a));

// Expect log function parameter to be int
const { log } = util((a: int) => String(a));

// Expect log function parameter to be object
const { log } = util((a: object) => String(a));

I am aware that the type can be specified in a generic way, but I am curious if the type declared in the parameter signature of the callback function can be passed along.

Answer №1

Give this a shot:

const utility = <U,>(customFunc: (arg:U) => string) => ({
  // I anticipate the type of parameter [p] for the log function to be inferred from the customFunc's parameter type
  log: (p: U) => console.log(customFunc(p))
});

Simply define a generic parameter and TypeScript will automatically deduce it

Answer №2

Using a generic type allows you to retrieve it

const util = <T>(handle: (p: T) => string) => ({
  // The log function's parameter [p] is expected to have the same type as the handle function's parameter
  log: (p: T) => console.log(handle(p))
});

// Expecting the log function parameter to be a string
const { log } = util<Number>((a) => String(a));
log(1);   // Parameter type: number

const { log: log1 } = util<String>((a) => String(a));
log1('1');    // Parameter type: string

const { log: log2 } = util<Object>((a) => String(a));
log2({});  // Parameter type: object

const { log: log3 } = util((a) => String(a));
log3('');   // Parameter type: any 

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

Develop a new flow by generating string literals as types from existing types

I'm running into a situation where my code snippet works perfectly in TS, but encounters errors in flow. Is there a workaround to make it function correctly in flow as well? type field = 'me' | 'you' type fieldWithKeyword = `${fiel ...

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Problem with moving functions from one file to another file via export and import

I currently have the following file structure: ---utilities -----index.ts -----tools.ts allfunctions.ts Within the tools.ts file, I have defined several functions that I export using export const. One of them is the helloWorld function: export const hel ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Angular 2 Ahead-of-Time compiler: all clear on the error front, yet a nagging feeling of

I've spent the last 72 hours trying to figure out how to make Ahead-of-Time compilation work for my Angular 2 rc.6 application. Currently, my application runs smoothly using Just-in-Time compilation. I've made sure to install all necessary depe ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

In the Angular Google Maps API, is it possible to update the attributes of <agm-marker> directly within the TypeScript code?

Currently, I am fetching markers from the database and displaying them on a map using Angular Google Maps (AGM) by utilizing the <agm-marker> tag. In my code snippet below, you can see how I fetch and store the markers in an array named markers in t ...

How to configure intellisense for a webpack bundle in an ASP.NET Core project

In my development process, I utilize webpack to transpile Typescript code into Javascript and combine it into a single Javascript file. This consolidated file is then incorporated into all of my asp.net core views. While the bundled code runs smoothly, unf ...

typescript function intersection types

Encountering challenges with TypeScript, I came across the following simple example: type g = 1 & 2 // never type h = ((x: 1) => 0) & ((x: 2) => 0) // why h not never type i = ((x: 1 & 2) => 0)// why x not never The puzzling part is w ...

Observable doesn't respond to lazy loaded module subscriptions

I am trying to understand why my lazy loaded module, which loads the test component, does not allow the test component to subscribe to an observable injected by a test service. index.ts export { TestComponent } from './test.component'; export { ...

What could be the reason for mocha failing to function properly in a project that is set up

During a unit test in my TypeScript project using mocha, I encountered an issue when setting the project type to module. The error message displayed is as follows: ➜ typescript-project yarn test yarn run v1.22.17 warning package.json: No license field $ ...

How to make a unique array of arrays in Javascript without any repeated elements

Hello fellow programmers! I'm diving into Javascript and facing a little challenge that I need help with. Let me share some data that I'm dealing with: <pre> [ [ { "id": 2759178563, "title": "Ergonomic Paper Computer", ...

"Omitting the parameter value when passing it to a directive in Angular

I recently developed a Directive in Angular7, but I encountered an issue when trying to pass a string value from the HTML to the directive. When using the following code snippet in my HTML: <ng-template [appValidatePermission]='CreateRole'&g ...

TSDX incorporates Rollup under the hood to bundle CSS Modules, even though they are not referenced

I have recently developed a React library with TSDX and you can find it here: https://github.com/deadcoder0904/react-typical This library utilizes CSS Modules and applies styles to the React components. Although the bundle successfully generates a CSS fi ...

Oops! An issue has occurred: Unable to locate a differ that supports the object '[object Object]' with the type 'object' within Angular

What am I doing wrong? It's working but I got this error in my console. My Model: export class Form { id: number; formTaxID: number; name: string; formYear: number; sectionID: number; createdAt?: Date; updatedAt?: Date; } My Service: ...

Transforming a selected option into a boolean value

Currently, I am delving into the world of Angular 2 and facing a particular issue: In my code, there is a select element designed to function as a boolean value: <select [(ngModel)]="caseSensitive"> <option>false</option> <o ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

What is preventing Apollo from achieving full transformation?

I have been struggling with an issue involving Apollo mutation for the past 2 days. Whenever I call a mutation on Angular Apollo generated code and subscribe to it, the subscription never completes. I am expecting a result from the server, but nothing is ...

`Adjusting video frame on canvas`

When I capture video from a user's camera and display it in a 1:1 square, I encounter an issue when trying to draw the picture to a canvas. The image is not drawn in the same location on the canvas. How can I resolve this problem? To see a live examp ...