typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? string : number;
  return (isTrue ? "Nice" : 20) as RETURN;
}

function funcCbCustom<T>(cb: (isTrue: boolean) => T) {
  const getFirst = () => cb(true);
  const getSecond = () => cb(false);

  return {
    getFirst,
    getSecond
  };
}

const result = funcCbCustom((isTrueInCb) => {
  return funcOneCustom(isTrueInCb);
});

I’m trying to figure out how to change the return types of funcCb automatically based on input.

  const result: {
    getFirst: () => string | number;
    getSecond: () => string | number;
}

Is there a way to achieve the following without using 'as'?

 const result: {
    getFirst: () => string;
    getSecond: () => number;
}

I want the return types to be inferred based on the function passed to funcCb. For example:

function funcTwoCustom<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? Date : string;
  return (isTrue ? new Date() : new Date().toString()) as RETURN;
}

Answer №1

I attempted a similar approach and it appears to be successful =)

function customFunc<T extends boolean = false>(isTrue: T) {
  type RETURN = T extends true ? string : number;
  return (isTrue ? "Cool" : 10) as RETURN;
}

function performCallback<T>(cb: (isTrueInCb: false) => number): { getString: string, getNumber: number } 
function performCallback<T>(cb: (isTrueInCb: true) => string): { getString: string, getNumber: number } 
function performCallback<T>(cb: (isTrueInCb: any) => T): { getString: T, getNumber: T } {
  const getString = cb(true);
  const getNumber = cb(false);

  return {
    getString,
    getNumber
  };
}

const finalResult = performCallback((isTrueInCb) => {
  return customFunc(isTrueInCb);
});

Check out this playground on TS site:

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

Merge two arrays based on date and sort them using Angular.js/JavaScript

I am facing a challenge where I have two JSON arrays, each containing a field named date. My goal is to compare the two arrays and merge them into a single array. Check out the code snippet below: var firstArr=[{'name':'Ram','date ...

Require assistance in accessing the second tab on a webpage using JavaScript tabs

Currently, I have a web page with two tabs that are initially hidden until the corresponding tab button is clicked. The click event is managed by jQuery. For example, let's assume that tab 1 is the default one when the page loads. Now, I am looking fo ...

What is the best way to bring in this interface from the React-Particles-JS library?

I have been attempting to segregate my parameters from my JSX within the react-particles-js library. I organize my parameters in an Object: let config = { "particles": { "number": { "value": 50 }, ...

What strategies can be used to refactor nested callbacks in node and effectively pass parameters to each function within the callbacks?

I am currently in the process of refactoring some JavaScript code within a Node environment, and I'm encountering difficulties when it comes to passing parameters to functions that serve as callbacks for other functions. Here is an example of my curre ...

Loading a unique shape using JSON within the KineticJS framework

Is there a way to load a unique custom shape using a Json file in Kinetic JS? The documentation I found only covers loading normal shapes. ...

The console displays "undefined" when formatting API data

I am attempting to format the data retrieved from an API since there is a lot of unnecessary information. However, when I try to display the formatted data in the console, it always shows as "undefined" or "null." I am importing and calling the fetch API ...

"Unexpected behavior: PHP+JS getElementById() function is returning an integer value instead of a

EDIT: Apologies for the PHP section not displaying correctly. I am attempting to extract a decimal value from PHP/HTML in JavaScript using getElementByID().value. However, despite the PHP value being decimal, it is represented as an integer in JavaScript ...

Managing errors in jQuery's .ajax function

Having some issues with jQuery.ajax() while trying to fetch an html code snippet from table_snippet.html and replacing the element in my html code. The error handler in jQuery.ajax() gets triggered instead of the expected success handler. <!DOCTYPE H ...

When invoking the jQuery ".load('pageName')" method, HTML pages are not loaded from the application cache

I have been working on incorporating the html5 offline caching functionality into our html pages, and everything seems to be running smoothly with jQuery version 1.4. However, I encountered a problem when I upgraded to jQuery 1.8. Specifically, issues aro ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...

Challenges with integrating Firebase with Ionic 3

After attempting to install firebase in my ionic 3 project using the command npm install firebase @angular/fire, I encountered numerous errors. It seems that there may be a compatibility issue with my version of Ionic (3) because the errors disappear when ...

Handling dynamic routes with React Router 4 and the 404 path

I have been working with the latest version of React Router (4) and have implemented a dynamic route configuration as described in the tutorial. The routes are functioning correctly, except for when I tried to add a 404 path following the tutorial's i ...

Ways to efficiently transfer multiple files from a server to a client using Express in NodeJS

I am working on a NodeJS server to transfer various files, such as images, css files, and js files, to clients. Currently, I have the following code snippet for sending individual files: app.get('/js/client.js', function (req, res) { res.sendF ...

cPanel is incompatible with node version 12.16.0

I am facing a dilemma regarding hosting my node API, which was built using node version 12.16.0, on cPanel. The available version for node in cPanel is 12.9.0 (Most recent). How should I proceed? Is the node version really a critical factor in this case? ...

JavaScript saves all URLs using a consistent format (http, https, www.)

As a junior backend developer, my experience with JavaScript is limited. I am attempting to standardize the format of stored URLs as shown below: www.hello.com hello.com http://hello.com https://hello.com Currently, if I input hello.com, it automatically ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Using PHP and MySQL to create checkboxes populated with data retrieved from a database, and then submitting two parameters

Hey there, I've been struggling with this issue for quite some time. I'm trying to create a list with checkboxes populated from a database that includes [checkbox of car id and value][brand][model]. The goal is to select two cars from the list, ...

A guide to customizing node names using vue-slider-component

I am facing an issue with the vue-slider-component. Below is the link to my current test module: template:` <div> <vue-slider v-model="value" :order="false" :tooltip="'always'" :process="false" ...