"The Promise of Generics in Typescript: Unlocking Unique Return

In my current project, I am working on implementing a function that will always return a fulfilled promise of the same "type" that is passed to it as a parameter.

This means that if I call the function with a boolean parameter, it should return a fulfilled Promise with a boolean value. The same goes for any other data type such as strings, numbers, etc.

Here's what I've attempted so far:

const createFulfilledPromise = <T>(val: T): Promise<T> => {
    return Promise.resolve(val);
};

I'm not certain if this is the most effective way to achieve this functionality, and I have encountered issues when trying to get a Promise<void>.

Any suggestions or advice on how to improve this implementation would be greatly appreciated.

Answer №1

Your code implementation appears to be correct, but one issue with using void is that the parameter is still expected. Instead, you can call it with undefined

const PromiseOK = <T>(val: T): Promise<T> => {
    return Promise.resolve(val);
};

PromiseOK<void>(undefined)

An alternative approach would be to utilize overloads for custom behavior when dealing with void:

function PromiseOK(): Promise<void>
function PromiseOK<T>(val: T): Promise<T>
function PromiseOK<T>(val?: T): Promise<T> {
    return Promise.resolve(val);
};

PromiseOK() // Promise<void>
PromiseOK(1) //Promise<number>

Although not very elegant, it is possible to have overloads with arrow functions as well:

const PromiseOK: {
    (): Promise<void>
    <T>(val: T): Promise<T>
} = <T>(val?: T): Promise<T> => Promise.resolve(val);

PromiseOK() // Promise<void>
PromiseOK(1) //Promise<number>

Answer №2

The original poster is seeking to correlate the Type of the parameter with the return value.

Nonetheless, if you desire a truly versatile promise where the return type is determined dynamically by the caller, consider using this approach.

const bar = <U>(baz: Baz): Promise<U> => {
  return new Promise<U>((resolve, reject) => {
    // assign any value with type U to resolve
    // for instance, API response: U
  });
};

// Example of how to use it
bar<CustomType>(someValueForBaz).then().catch();

Answer №3

Here is an example of how it should appear:

An example function using Promise in TypeScript:
function PromiseOK<T>(val: T): Promise<T> {
    return Promise.resolve(val);
};

If you prefer to use the fat arrow notation:

Another example with fat arrow notation:
const PromiseOK = <T extends any>(val: T): Promise<T> => {
    return Promise.resolve(val);
};

The usage of T extends any also works for void.

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 are the steps to fix the error stating that 'loginError.data' is an unknown type?

Recently delving into typescript, I decided to test the waters with nextjs, rtk query, and antd. However, while attempting to access error within useLoginMutation using the property error.data.message, it was flagged as type unknown. To tackle this issue, ...

What is the best way to overload a function based on the shape of the argument object in

If I am looking to verify the length of a string in two different ways (either fixed or within a specific range), I can do so using the following examples: /* Fixed check */ check('abc', {length: 1}); // false check('abc', {length: 3}) ...

What is the best way to change a Date stored in an array to a string format? [angular4]

Presented here is an array with the data labeled dateInterview:Date: public notes: Array<{ idAgreement: string, note: string, dateInterview: Date }> = []; My goal is to send this array to the server where all values of dateInterview need to be co ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

How to utilize the async pipe on an observable<Object> and connect it to a local variable in the HTML using Angular

Hey there! So, I have this observable called user$ which has a bunch of properties such as name, title, and address. component{ user$:Observable<User>; constructor(private userService:UserService){ this.user$ = this.userService.someMethodRet ...

Angular does not allow the transfer of property values from one to another

As of late, I have delved into learning Angular but encountered an issue today. I have the following Component: import { Component, OnInit } from '@angular/core'; import { SharedService } from '../home/shared.service'; import { IData } ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...

Encountering error TS2304: Cannot resolve name 'classes' when attempting to apply styling in React using Typescript

I'm having trouble customizing the styles on my website, specifically when trying to add a custom className. Error Message: Cannot find name 'classes'. TS2304 Below is the code I am currently working with: import React from 'react& ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Storing a string in a variable within Typescript

Attempting to read an XML file in Typescript using some JavaScript code, with the goal of adding the text content to a local variable. The code snippet is as follows: import { Injectable } from '@angular/core'; @Injectable() export class Jsonre ...

Creating a nested/child route structure within the Angular 2 router

Looking to implement nested routing for mypage/param1/1/param2/2 format in the URL. The first parameter is represented by 1 and the second one by 2. It's imperative that there are always two parameters, otherwise an error should be displayed. However, ...

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

Error: The term 'makeStyles' cannot be found in the '@material-ui/core' module after installing Material-ui-pickers

Can anyone help me with using the inlineDatePicker components from Material UI pickers? I found them here: After running the npm -i command, I encountered an error during compilation: Failed to compile. ./node_modules/material-ui-pickers/dist/material-u ...

Is it advisable to move operations outside of the useEffect hook?

Is it advisable to move code outside of the useEffect function in React? function BuyTicket(props: any) { useEffect(() => { //.. }, [eventId, props.history]); // IS IT RECOMMENDED TO PUT CODE HERE? const userNameL ...

Error happens while running the setInterval loop in the code execution

I encountered a peculiar issue while developing a 2D game in Angular. The function in my component calls an async function to load the sprites, then executes the game loop in the callback GameComponent.ts: constructor(private loader: AppService, privat ...

Bluebird's premature return in express/mongoose is causing unexpected issues

I am a beginner when it comes to promises and I am facing an issue with the code below. I believe it might be due to the way I need to set up my custom methods in order to work with promises. My Promise library of choice is bluebird. I am attempting to re ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this: async findOne(id: string) { return await this.gameModel.findById(id); } async update(id: string, updateGameDto: UpdateGameDto) { const game = await this.findOne(id) // This code snippet prints al ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

Altering or including new space variables within a custom Chakra-ui theme

Looking to customize spacing variables in a Chakra UI theme? I have successfully implemented various extensions, but changes to spacing are not being applied. const config: ThemeConfig = { initialColorMode: 'light', useSystemColorMode: false ...