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