Is there a way to ensure that the return type of a generic function is always optional in Typescript?

Is there a way to ensure the return type is always optional from a generic return type in functions?

I specifically need the return types (data & error) to be optional at all times since one of them will always be undefined.

TypeScript declarations

import getConfig from 'next/config';
import axios, { AxiosRequestConfig } from 'axios';

import { MethodCall } from './methods';

const { publicRuntimeConfig } = getConfig();


export interface HttpReturnSuccess<TData = unknown> {
    data: TData;
    error: undefined;
    isError: false;
}

export interface HttpReturnError<TError = unknown>
     {
    data: undefined;
    error: TError;
    isError: true;
}

export type HttpReturn<TData = unknown, TError = unknown> =
    | HttpReturnSuccess<TData>
    | HttpReturnError<TError>;

export interface HttpProps<TPayload> {
    method: MethodCall;
    path: string;
    data?: TPayload;
    config?: AxiosRequestConfig;
}

When the function returns an object {data: Data, error: Error}, I want both data and error to be optional. For example -> {data?: Data, error?: Error}

const baseUrl = publicRuntimeConfig.baseUrl;

export const internalHttp = async <Data = unknown, Payload = unknown, Error = unknown>(
    props: HttpProps<Payload>
): Promise<HttpReturn<Data, Error>> => {
    const { method, path, data: body, config } = props;

    const returnedValue = {
        data: undefined,
        error: undefined,
        isError: false,
    };

    const url = baseUrl + ':' + path;

    const options = [body, config];

    if (method === MethodCall.Get) options.shift();

    try {
        const { data } = await axios[method]<Data>(url, ...options);

        returnedValue.data = data as Data;
    } catch (error) {
        returnedValue.error = error as Error;

        returnedValue.isError = true;
    }

    return returnedValue;
};

const {data} = internalHttp<{name: "amed"}>() 

// I expect data to be Data | undefined. 

// TypeScript suggests -> data.name | What I want -> data?.name -> this behavior

Answer №1

To define the return type for a function, you can simply include it within the function declaration like this:

export const customApiCall = async <
    Response = unknown,
    Data = unknown,
    Error = unknown
>(
    options: ApiOptions<Data ,Error>
) : {response: Response | undefined, error: Error | undefined, hasError: boolean} => { ... }

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 encountered while attempting to load SWC binary for win32/ia32 in a Next JS application

Upon installing a Next.js app using the command npx create-next-app@latest, I encountered an error while running the app. Can anyone explain why this error occurred and provide a solution? PS D:\New folder\my-app> npm run dev [email pr ...

React-query: When looping through useMutation, only the data from the last request can be accessed

Iterating over an array and applying a mutation to each element array?.forEach((item, index) => { mutate( { ...item }, { onSuccess: ({ id }) => { console.log(id) }, } ); }); The n ...

Combining Nextjs and Expo in a Monorepo may result in the error message "Invalid Hooks Call."

I have organized a monorepo with 4 different packages as follows: . ├── lerna.json ├── package.json ├── packages │ ├── admin-> Basic CRUD for backend with Nextjs │ ├── mobile-> Expo app │ ├── server-> ...

Having trouble with redundant code while updating state in ReactJS - React JS

Currently, I am working on a prayer times web app using reactJS (nextjs). To achieve this, I first fetch the geolocation coordinates and then retrieve the city and country name based on these coordinates. Following that, I obtain the prayer times for the s ...

The error message "Type 'string | number' is not assignable to type 'number'" indicates a type mismatch in the code, where a value can be either

I encountered an error code while working with AngularJS to create a countdown timer. Can someone please assist me? //Rounding the remainders obtained above to the nearest whole number intervalinsecond = (intervalinsecond < 10) ? "0" + intervalinseco ...

Is it possible to implement the new Next.js middleware in a custom hosting environment?

Currently, I am working on an application using Next.js specifically for user authentication via JWT's and then redirecting them to our main web application. Previously, before the release of version 12 of Next.js, I utilized next-connect to execute a ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

retrieve the values from an array and showcase them in a formatted table

I need assistance in displaying the values stored in the array isReferralAvailable from my Google Firestore database. To provide a visual representation, here is an image of my Firebase database structure: The challenge lies in fetching the values of isRe ...

Reusing methods in Javascript to create child instances without causing circular dependencies

abstract class Fruit { private children: Fruit[] = []; addChild(child: Fruit) { this.children.push(child); } } // Separate files for each subclass // apple.ts class Apple extends Fruit { } // banana.ts class Banana extends Fruit { } ...

While using Angular CLI on GitLab CI, an error occurred indicating that the custom rule directory "codelyzer" could not be

ng lint is throwing an error on Gitlab CI stating: An unhandled exception occurred: Failed to load /builds/trade-up/trade-up/common/projects/trade-up-common/tslint.json: Could not find custom rule directory: codelyzer. The strange thing is that ng lint ru ...

Next.js fails to properly render external links when utilizing the Link component

It was quite surprising to discover that a basic Link component doesn't function as expected in Next.js when attempting to use it with an external URL and HTML Button tag within. Here is my attempt at solving this issue: Attempt 1: <Link href="h ...

Threading in Node.js for Optimized Performance

Having trouble making axios calls in worker threads Hello, I'm working on a Node.js application and attempting to utilize worker threads for one specific task. Within the worker thread, I need to make an axios call, but I keep encountering an error w ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

utilizing tabview for component replacement

Having trouble changing components in Angular 7 with PrimeNG tabview tabs? Need some assistance? I have a setup with 3 components, and I want to switch between them when clicking on the panel inside the tabview. I've tried using onchange functions i ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

You are limited to typing only 1-2 characters in the input field, however, you are able to paste text that exceeds this limit. This functionality is achieved through

Update: I managed to resolve my problem by creating a separate component for the dialog I attempted changing the type to text instead of string and removing the grid in the styling, but encountered the same issue. The onchange function is causing the prob ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Error occurs in the compiler when a variable is utilized as a function

I'm currently facing an issue while compiling Typescript where the compiler is throwing an error: TypeError: myVariable is not a function at Object.<anonymous> (/home/anon/Desktop/Typescript/main.js:37:1) at Module._compile (internal/mo ...

Passing data to a child component using Context in React is not working

I have a parent component where I am storing data in an array of objects and then passing it to another component through Context. Here is how my parent component looks: export type HistoryData = { input: string; date: string; ...

Discover the power of utilizing the reduce function to extract the value of a specific field within an array of Objects

In the following example, we have an object with 3 forms: formA, formB, and formC. Form A and B are objects, while formC is an array of objects that can contain multiple items. const object: { "formA": { "details": {}, ...