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

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

Slide in the Toggle Effect to Your Navigation Menu

Seeking help with enhancing my jQuery dropdown menu to include a slide down toggle effect similar to this example: http://jsfiddle.net/LaSsr/188/. Any assistance in applying this slide effect to the following JSfiddle would be greatly appreciated. Thank yo ...

I am looking to dynamically insert a text field into an HTML form using jQuery or JavaScript when a specific button is clicked

This is my code snippet: <div class="rButtons"> <input type="radio" name="numbers" value="10" />10 <input type="radio" name="numbers" value="20" />20 <input type="radio" name="numbers" value="other" />other </div> ...

How can one generate an array containing all attributes found in the HTML of a website?

I have a project idea where I want to be able to input a hyperlink address and then get a list of attribute contents as the output. For instance, if I input a Netflix genre hyperlink for Adventure Movies, I'd like to receive a list with all the movie ...

Make sure to always keep all stars contained within a div element

How can I keep five stars inside a div even when the screen size is small? I have created a div with an image and I want to place five stars within that div. However, as I reduce the size of the screen, the stars come out of the box. Is there a way to en ...

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

Storing the blob received from an AJAX call into Azure Blob Storage may result in a corrupted image

When I send a PDF to my vendor's API, they return a .png file as a blob (note: see update 2 regarding the data type being returned). I want to store this in Azure Blob Storage. However, when using the code below, the uploaded file becomes corrupted. ...

Tips for retrieving multiple data outputs from an ajax success function

Within my project, I have two separate JavaScript files named myJs1.js and myJs2.js. One of the methods in myJs1.js is invoking a method from myJs2.js. My goal is to retrieve the values r1 and r2 into the results (within myJs1.js). I attempted to achiev ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Having trouble sending the selected value from a dropdown list to the server using $.ajax

I am embarking on my first project using JQuery (jquery-3.0.0.min.js) and JavaScript. My goal is to build a straightforward web form that connects to a database through a Web API. The form consists of various input text fields and two select dropdowns. ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Load image asynchronously using a mirror server in React/Next.js with a set timeout time

For my website, I have decided to store all of my images on IPFS, which are pinned successfully. This has helped reduce traffic and keep costs within the free tier offered by my hosting provider. However, at times the IPFS url may not load fast enough dep ...

What will be provided as the outcome?

I have recently started learning express.js. The following code snippet is taken from the router library of express.js. var proto = module.exports = function(options) { options = options || {}; function router(req, res, next) { router.handle(req, ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

What is the best method to extract information from JavaScript tables using Python and Selenium?

As a beginner in Python, JavaScript, and Web-Scraping, I am facing the challenge of extracting data from tables on a specific webpage (https://www.mcmaster.com/cam-lock-fittings/material~aluminum/) and saving it into a csv file. Initially, I attempted to ...

Analysis of cumulative revenue using Palantir Foundry Function

I am in need of creating a function that can transform raw data into target data. The raw data consists of a table with columns for customer, product, and revenue, while the target data includes customer, revenue, and cumulative revenue. customer produ ...

How can I attach a click event to the left border of a div using jQuery?

I am wondering about a div element <div id="preview"> </div> Can anyone suggest a method to attach a click event specifically to the left border of this div? Your help is greatly appreciated. ...