Encountering TypeScript Error when Using Hooks (possible type mismatch?)

Currently, I am developing a custom `useProject` hook in TypeScript that is utilizing a function defined in `useProjectFunctions.ts`.

While working on the `useProject` hook, I encountered a TypeScript error indicating type mismatch, although I am unable to identify any discrepancies.

useProjectFunctions.d.ts

export declare type GetImageUploadToken = ({ ...params }: {
    organisationId: string,
    projectId: string,
    imageName: string,
    isAdminRequest?: boolean,
}) => {
    status: 'success';
    tokenId: string;
}

useProjectFunctions.ts

export function useProjectFunctions() {
    const { functions } = useFirebase();

    async function getImageUploadToken({ ...params }: Parameters<GetImageUploadToken>[0]) {
        const response = httpsCallable<any, ReturnType<GetImageUploadToken>>(functions, ProjectFunctions.GET_IMAGE_UPLOAD_TOKEN);
        return (await response({ ...params })).data;
    };

    return {
        getImageUploadToken
    };
}

useProject.ts

export function useProject() {
    const { getImageUploadToken } = useProjectFunctions();

    return {
        addImage: () => addImage({ getImageUploadToken })
    };
}

async function addImage({ getImageUploadToken }: {
    getImageUploadToken: GetImageUploadToken;
}) {
    const tokenCallResponse = getImageUploadToken({
        organisationId: 'orgId1',
        projectId: 'projId1',
        imageName: 'fileName',
        isAdminRequest: false
    });
}

When running useProject.ts, TypeScript throws an error at the

addImage: () => addImage({ getImageUploadToken })
line:

The assigned type '({ ...params }: { organisationId: string; projectId: string; imageName: string; isAdminRequest?: boolean; }) => Promise<{ status: "success"; tokenId: string; }>' does not match the expected type 'GetImageUploadToken'.

The returned type 'Promise<{ status: "success"; tokenId: string; }>' is missing properties 'status' and 'tokenId' from the expected type '{ status: "success"; tokenId: string; }'.

This discrepancy originates from the property 'getImageUploadToken' declared in '{ project: PrivateProjectInterface; setProject: Dispatch<SetStateAction>; file: File; admin?: boolean; getImageUploadToken: GetImageUploadToken; storage: FirebaseStorage; }'

Can someone explain the true meaning of this error and suggest a solution?

Answer №1

Your GetImageUploadToken type is an object, but the getImageUploadToken type is a promise that resolves to GetImageUploadToken when it completes.

To resolve this issue, update the type in addImage from getImageUploadToken: GetImageUploadToken to getImageUploadToken: Promise<GetImageUploadToken>

By making this change, TypeScript will recognize that you are passing an asynchronous function to addImage

Don't forget to await the asynchronous getImageUploadToken function by updating the function call to const tokenCallResponse = await getImageUploadToken({

If you're still unsure, consider brushing up on asynchronous functions and promises in JavaScript

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

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

Testing the creation of elements dynamically with jestLooking into jest for dynamically adding

Attempting to test a dynamic element using TypeScript, but struggling to understand the process. Can anyone offer guidance? Below is the TypeScript file: export default class MyClass { constructor(){ this.render(); } render() { ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

Troubleshooting problem in Grunt-TS, Grunt, watch/compile, and Dropbox integration

UPDATE: Recently, I've been experiencing some issues with another computer when it comes to watching and compiling. It seems like the tscommandxxxxxx.tmp.txt files that are generated during compilation might be causing the trouble... sometimes they ar ...

Issue with MathJax rendering within an Angular5 Div that's being observed

I am trying to figure out how to enable MathJax to convert TeX to HTML for elements nested within my div. Here is the current content of app.component.html: <p> When \(a \ne\) It works baby </p> <div class="topnav"> ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

What is the correct way to format React's dispatch function in order to utilize a "then" method similar to a Promise?

I'm working on a simple app that dispatches an action upon first load to populate the store. However, I'm facing an issue with trying to run a then method on dispatch, as typescript is throwing errors. (As per redux's documentation, the ret ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

The 'split' property is not found on the 'Int32Array' type

ERROR located in src/app/account/phone-login/phone-login.component.ts(288,53): error TS2339: Property 'split' is not a valid property for type 'string | Int32Array'. Property 'split' cannot be found on type 'Int32Array& ...

Why are the class variables in my Angular service not being stored properly in the injected class?

When I console.log ("My ID is:") in the constructor, it prints out the correct ID generated by the server. However, in getServerNotificationToken() function, this.userID is returned as 'undefined' to the server and also prints as such. I am puzz ...

What is the best way to toggle a card within a collection of cards using Angular?

Wishing you a wonderful day! I simply desire that when I click on a card, only that specific card flips over. But unfortunately, all the cards flip when I click on just one. HTML https://i.sstatic.net/B0Y8F.png TypeScript https://i.sstatic.net/mVUpq.png ...

An issue occurred when clicking on a line due to the filter

Issue at Hand: Currently, I am facing a problem where selecting an item from the list by clicking on the button leads me to access the information of a different item when the filter is applied. Desired Outcome: I wish to be able to access the correct inf ...

What causes this conditional type to function correctly in a static context while failing in a dynamic setting

I have created a unique conditional type that accurately generates a union of valid array indices: type ArrayIndices< N extends any[], Acc extends number[] = [] > = Acc['length'] extends N['length'] ? Acc[number] : ArrayIn ...

Incorporating a CSS Module into a conditional statement

Consider the following HTML structure <div className={ `${style.cell} ${cell === Player.Black ? "black" : cell === Player.White ? "white" : ""}`} key={colIndex}/> Along with the associated CSS styles .cell { ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...

Experiencing a bug in my express application: TypeError - Unable to access properties of undefined (reading 'prototype')

I've encountered the TypeError: Cannot read properties of undefined (reading 'prototype') error in my javascript file. Despite researching online, it seems that many attribute this issue to importing {response} from express, but I am not doi ...

Whenever I attempt to bring in AngularFireModule, an error promptly appears

I am experiencing some errors when trying to import AngularFireModule and initialize the app with environment.firebaseConfig. I have tried to solve the problem but without success. Can anyone provide guidance on what steps I should take? @NgModule({ decl ...

"Creating a Typescript property that is calculated based on other existing properties

I am working on a Typescript project where I have a basic class that includes an `id` and `name` property. I would like to add a third property called `displayText` which combines the values of these two properties. In C#, I know how to achieve this using ...

The Angular tutorial for the "Tour of Heroes" is experiencing issues with aligning the heroes' list properly

I am currently working on the Angular tour of heroes tutorial. However, I am facing an issue when trying to display the list of heroes as it appears like this: https://i.sstatic.net/AGnzJ.png It is strange because even though the CSS/HTML/TS code from the ...