The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function.

interface Request {
    ids: string[];
    resolver: () => void;
    promise: Promise<unknown>
}

class Foo {
    public requests: Request[] = [];

    public createPromise = (ids: string[]) => {
        let resolver;

        const promise = new Promise((r) => { resolver = r; });

        this.requests.push({ ids, resolver, promise });

        return promise;
    };
}

However, when trying to add the object to the requests list, TypeScript throws an error regarding the resolver:

Type 'undefined' is not assignable to type '() => void'.ts(2322)

This means that the resolver variable inside the promise constructor is interpreted as undefined.

Answer №1

If you want to make some adjustments, here are a few pointers:

  • Make sure the local variable resolver has a specific type that matches the request interface.
  • It's important to assert (!) that the variable will be assigned. This is because the assignment occurs in a callback function and TypeScript cannot predict when this function will be executed. Another class could potentially have a similar constructor with a callback that is not called immediately.
  • The value argument in the request interface function should match the type of the promise. If you don't need a resolved value, you can use Promise<void> instead.
interface MyRequest {
    ids: string[];
    resolver: (value: unknown) => void;
    promise: Promise<unknown>;
}

class Bar {
    public requests: MyRequest[] = [];

    public createNewPromise = (ids: string[]) => {
        let resolver!: (value: unknown) => void;

        const promise = new Promise((r) => { resolver = r; });

        this.requests.push({ ids, resolver, promise });

        return promise;
    };
}

(Changed interface name to avoid clash with fetch API Request.)


Illustration of the assignment concern:

class DummyPromise {
  constructor(executor) {
    // *silence*
  }
}

let resolverOne;
new Promise(r => resolver1 = r);
console.log(resolverOne); // function () ...

let resolverTwo;
new DummyPromise(r => resolver2 = r);
console.log(resolverTwo); // undefined

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

Error: the attempt to execute the mongoose connection function has failed due to it not being recognized as a valid function

Hey there, I'm encountering the error TypeError: mongoose__WEBPACK_IMPORTED_MODULE_15___default.a.connect is not a function import mongoose from "mongoose"; const dbURI = 'myurlstuffhere'; mongoose.connect(dbURI , {useNewUrlParser: ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Restrict the parameter type using a type predicate

How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type na ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

`Property cannot be redefined: __internal__deprecationWarning` detected in a Shopify Hydrogen development project

Recently, while working on my Shopify Hydrogen project using Remix and Typescript, I encountered a sudden error when running npm run dev. Everything was functioning perfectly just 5 hours ago, but after returning from dinner, the app refuses to launch. ╭ ...

What is the best way to determine the type of a key within an array of objects

Suppose I have the following code snippet: type PageInfo = { title: string key: string } const PAGES: PageInfo[] = [ { key: 'trip_itinerary', title: "Trip Itinerary", }, { key: 'trip_det ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

Substitute this.bindMethod for function component

I have a class component that is structured like this: interface MyProps { addingCoord: any resetCoords: any } interface MyState { x: any y: any } class DrawerOld extends React.Component<MyProps, MyState> { width: number height: number ...

Setting up Webpack for my typescript React project using Webpack Version 4.39.2

I have been given the task of fixing the Webpack build in a project that I am currently working on. Despite not being an expert in Webpack, I am facing difficulties trying to make it work. The project has an unconventional react frontend with typescript. I ...

ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When ...

Understanding Typescript event handling in React

Encountering issues when attempting to build my React/Typescript app using the MouseEvent type in an event handler: private ButtonClickHandler(event: MouseEvent): void { ... } The error message received is as follows: error TS2322: Type '{ onCl ...

Error: The binding element titled implicitly possesses a type of 'any'

Encountering the following issue: ERROR in src/components/Header.tsx:6:18 TS7031: Binding element 'title' implicitly has an 'any' type. 4 | 5 | 6 | const Header = ({title}) => { | ^^^^^ 7 | return( 8 | ...

Loop through the information retrieved from the alertController

I'm currently facing an issue regarding accessing data in my alert controller let alert = this.alertCtrl.create({ title: 'Edit Index', inputs:this.customIndexes, buttons:[ { text: 'Cancel', role: 'cancel ...

What is the most suitable data type to represent an empty object?

When I declared the return type of the function below as {}, eslint flagged an error stating not to use {} as a type because it actually means "any non-nullish value". After understanding the meaning behind this error, I realize that specifying return typ ...

Extra assistance might be required to manage the output from these loaders

I'm in the process of developing a State Management Library for ReactJs. However, when I integrate it into my React project (built with create-react-app), an error is thrown: Failed to compile. path/to/agile/dist/runtime.js 116:104 Module parse faile ...

Nullable Object in Vue 3 Composition API

I am utilizing the Vue 3 Composition api along with Typescript to create pinch zoom functionality using the HammerJS package. In my Vue application, I am attempting to replicate a functional example implemented in JavaScript from CodePen: https://codepen. ...

Inject an asynchronous callback into the constructor of a class by leveraging TypeScript and Node with Passport integration

Currently, I am utilizing the passport-http authentication library. The issue at hand is that its documentation makes use of callbacks while my implementation involves TypeScript classes with async/await functionalities, thus causing uncertainty regarding ...

Using Angular: A guide to setting individual values for select dropdowns with form controls

I am working on a project that involves organizing food items into categories. Each item has a corresponding table entry, with a field indicating which category it belongs to. The category is represented by a Guid but displayed in a user-friendly format. C ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...