Currently, I am in the process of developing an API model that has the capability to provide two different types of outputs depending on whether the response was returned correctly or not.
If the response is correct:
IApiResponse<T>
, where T denotes the desired data type for the output.If the response is wrong/error: The returned response will be of type
IApiResponse<IApiError>
.
export interface IApiResponse<T> {
data: T | IApiError
originalResponse: AxiosResponse<any, any> | null
ok: boolean
statusCode: number | undefined
error: string | null // represents our own error system
attribute: string | null // represents our own error system
errorDetail: string | null // represents our own error system
}
In this setup, the data can either match the specified type when the response function is executed, or it can correspond to an error type if there are any issues. The structure for the error type is defined as follows:
export interface IApiError {
type: string
errors: {
code: string
detail: string
attr: string
}[]
}
Upon calling my function and receiving a response, the type of the response appears as 'undefined,' which necessitates the utilization of a type guard to distinguish between IApiResponse<T>
and IApiResponse<IApiError>
. A simplified implementation of this concept is provided below (additional checks may also be conducted, with the 'ok' value serving as a key indicator).
export function isSuccessResponse<T>(response: any): response is IApiResponse<T> {
return response.ok
}
However, when attempting to employ this type guard within my application, the inferred type becomes 'never.'
if (isSuccessResponse<IAvailableSport[]>(response)) {
console.log(typeof response)
}
Although I have confirmed that the response is indeed accurate and contains the 'ok' property set to true, the type displayed by VS Code shifts to 'never' upon hovering over it.
Could there be an oversight on my end? Any insights would be greatly appreciated!