Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is greater than 1, and the second one should return Promise<T> if limit equals 1. Is there a way to define this behavior, or perhaps an alternative approach?

public async select<T extends any>(limit: number): Promise<Cursor<T>>

public async select<T extends any>(limit: number): limit is 1 && Promise<T>

public async select<T extends any>(...args: any[]): Promise<T | Cursor<T>> {
  // Perform query and return the Promise
}

Answer №1

To achieve the desired effect, you can utilize a numeric literal type in your overload like this:

class Cursor<T>{}
class O {

    public async select<T extends any>(limit: 1): Promise<T>
    public async select<T extends any>(limit: number): Promise<Cursor<T>>


    public async select<T extends any>(...args: any[]): Promise<T | Cursor<T>> {
        return null as any

    }
}
let o = new O();
let s = o.select(1) // Promise<{}>
let m = o.select(2) // Promise<Cursor<{}>>

It's important to note that this approach will only work effectively when passing the constant value of 1 to the function. Using other variables could lead to confusion and potential issues.

let n = 1;
o.select(n);// Since n is a number, its types as a Promise<Cursor<{}>> 
const constOne = 1;
o.select(constOne);// This will result in Promise<{}>

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

What is the preferred method for transferring server-side data to JavaScript: Using Scriplets or making an AJAX call?

At the server side, there is a property file that contains a list of words separated by commas. words.for.js=some,comma,separated,words The goal is to convert these words into a JavaScript array. var words = [some,comma,separated,words]; There are two ...

Ensure that clicking on various links will result in them opening in a new pop-up window consistently

I am facing an issue with my HTML page where I have Four Links that are supposed to open in separate new windows, each displaying unique content. For instance: Link1 should open in Window 1, Link2 in Window 2, and so on... The problem I'm encounter ...

Activate a button with jQuery when a key is pressed

Currently, I have two buttons set up with jQuery: $('#prev').click(function() { // code for previous button }); $('#next').click(function() { // code for next button }); My goal now is to implement a .keypress() handler on the ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

Unable to load images on website

I'm having trouble showing images on my website using Node.js Express and an HBS file. The image is not appearing on the webpage and I'm seeing an error message that says "GET http://localhost:3000/tempelates/P2.jpg 404 (Not Found)" Here is the ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

What could be causing the $httpProvider.interceptors to unexpectedly return an 'undefined' value?

Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors. This is the structure of my app: var app = angular.module("restaurantList", []); The yelpAPI service handles authenticatio ...

Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

The image slideshow on W3 Schools displays images in a stacked formation

Utilizing this code snippet from W3 Schools to incorporate an image slideshow into my web project. However, upon page load/reload, the images appear stacked vertically rather than horizontally (one above and one below). The slideshow functions properly aft ...

When a specific option is selected in a `select` element with the `multiple` attribute, activate the change event

Is it possible to trigger a change event on individual options within a standard select element using jQuery or another method? I want the change event to be triggered on the option elements themselves rather than on the select element, as multiple options ...

Tips for ensuring a function in Angular is only executed after the final keystroke

I'm faced with the following input: <input type="text" placeholder="Search for new results" (input)="constructNewGrid($event)" (keydown.backslash)="constructNewGrid($event)"> and this function: construct ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...

Angular, PHP, and MySQL working together to establish database connectivity

Greetings! I am facing some challenges with a small project involving mySQL and PHP for the first time. My main focus right now is on establishing connectivity. Despite following various tutorials, I have been unable to connect to the database and keep enc ...

Dropzone JavaScript returns an 'undefined' error when attempting to add an 'error event'

When using Dropzone, there is a limit of 2 files that can be uploaded at once (maxFiles: 2). If the user attempts to drag and drop a third file into the Dropzone area, an error will be triggered. myDropzone.on("maxfilesexceeded", function(file){ a ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

Encountering an unknown provider error in AngularJS while using angular-animate

Upon removing bower_components and performing a cache clean, I proceeded to reinstall dependencies using bower install. However, the application failed to load with the following error message: Uncaught Error: [$injector:unpr] Unknown provider: $$forceRefl ...

Store data in LocalStorage according to the selected value in the dropdown menu

Can you help me understand how to update the value of a localstorage item based on the selection made in a dropdown menu? <select id="theme" onchange=""> <option value="simple">Simple</option> <option valu ...

Props does not solely rely on Vue.js for data feeding

My journey with learning vue has just started, and I recently incorporated a prop into my vue component. At first glance, the code appeared to be correct, but then something unexpected occurred. import Vue from 'vue'; import App from './A ...