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

How can I apply both Css and Bootstrap styles to an element in Next.js?

I'm having trouble incorporating the Bootstrap class sticky-top into another CSS style element. I attempted to achieve the same effect without Bootstrap by adding position: sticky, top: 0 in the CSS, but it didn't work as expected. The issue aris ...

Create a recursive array structure that contains two distinct data types and specific guidelines

I have a unique array structure where the odd index always contains elements of TypeA and the even index always contains elements of TypeB. It is guaranteed that this array will always have an even length, never odd. The data structure of this array must ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

Using TypeOrm QueryBuilder to establish multiple relations with a single table

Thank you for taking the time to read and offer your assistance! I am facing a specific issue with my "Offer" entity where it has multiple relations to "User". The code snippet below illustrates these relationships: @ManyToOne(() => User, (user) => ...

The process of building paths fails when generating static parameters along with exporting static data

I am currently developing a Next.js Project and facing an issue with building the page using output: export in the Config File. The code snippet below shows how I am using generateStaticParams: export async function generateStaticParams() { const paths ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Obtain the appropriate selection in the dropdown based on the model in Angular

I am working on a dropdown menu that contains numbers ranging from 1 to 10. Below is the HTML code for it: <div class="form-group"> <label>{{l("RoomNumber")}}</label> <p-dropdown [disab ...

How does the Next.js 14 App router facilitate communication between the Client component and Server Actions?

Upon first inspection, I thought that Server Actions were simply functions written on the server to be executed by other server code or Server Components. https://i.stack.imgur.com/zgCDl.pngfrom NextJs docs To my surprise, I discovered that a Server Acti ...

There is no such property - Axios and TypeScript

I am attempting to retrieve data from a Google spreadsheet using axios in Vue3 & TypeScript for the first time. This is my initial experience with Vue3, as opposed to Vue2. Upon running the code, I encountered this error: Property 'items' does ...

An error occurred in retrieving the server side props: Unexpected character '<' found in JSON data at position 0

I am currently working with next.js and I am trying to retrieve data from my data1.json file using getStaticProps(). However, I am encountering an error: FetchError: invalid json response body at http://localhost:3000/data/data1.json reason: Unexpected t ...

Struggling to display the results of both methods in useEffect, but only one is showing up

I'm encountering an issue while attempting to render two methods in useEffect. Both methods are being rendered, but the content of the first method is somehow being replaced by the second method. In summary: I only see the output of the second method ...

Having continual issues with OAuthCreateAccount error on Next.js with Next Auth using Google as the provider

I have successfully set up next-auth with the GoogleProvider on my local environment. However, when trying to run it in production, I encountered an OAuthCreateAccount error: api/auth/signin?error=OAuthCreateAccount The error message prompts me to "Try s ...

I'm in the process of constructing a create-next-app and I need to retrieve data from a web API. However, I'm unsure of the best place to securely store the API key

I am working on building a create-next-app that will retrieve data from the News Catcher API and display it within my application. I have obtained an API key to access the News Catcher API. However, I am unsure of where to securely store the API key and h ...

Tips on sorting a nested array in a React TypeScript project

Hey there! I currently have a working filter in React that utilizes a List (I am using Mantine.dev as my CSS template): <List> {locations.filter(location => { const locServices: Service[] = []; location.services.forEach(service => { ...

How do I go about mocking a function from a third-party nodejs module when using TypeScript with jest?

I need help with mocking a function from a third-party node module in jest, specifically the fs.readFileSync() function. I have come across several examples online, but I haven't found one that incorporates TypeScript. To illustrate my question, I hav ...

What sets iron-session apart from next-auth?

What are the advantages of using iron-session over next-auth? Does next-auth support traditional username/password log-in as well as Social log-ins, whereas iron-session only supports the former? ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

What is the best way to transfer data from a server component to a client component in a Next.js 14 application router?

Looking for a way to transfer data from the server component to the client component in Next.js 13 app router? In my page.tsx file, I am making a call to an external API that retrieves the city of the person. Now, I need to pass this city data to the clie ...

Error: Unable to access 'clientModules' property as it is undefined

When running the project using npm run dev, everything works fine. However, I encountered errors when deploying with vercel --prod after generating a production build and starting the app with next start. Initially, I received a TypeError: Cannot read pro ...