I am implementing an API model that can return two possible types of outputs based on if the response was returned correctly or not.
-
If the response was correct:
IApiResponse<T>
where T is the type that you wish your data to be returned in. -
If the response was wrong/error:
IApiResponse<IApiError>
will be the type of the returned response.
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
}
As you can see the data can either be of the type that was passed in when the response function was triggered or an error type if there is any error. The definition for that is:
export interface IApiError {
type: string
errors: {
code: string
detail: string
attr: string
}[]
}
Now when I call my function and get my response I will get the response as an undefined type which I then use a type guard to check if the returned response is of the IApiResponse<T>
type or of the IApiResponse<IApiError>
. This is the below simplified implementation of that (there are more checks that are done but for all intents and purposes, reading the ok value will tell me the type of the response).
export function isSuccessResponse<T>(response: any): response is IApiResponse<T> {
return response.ok
}
However if I try to use this type guard in my actual application the type is narrowed to never.
if (isSuccessResponse<IAvailableSport[]>(response)) {
console.log(typeof response)
}
I have verified that the response is in fact actually correct and has the ok property set to true. But VS Code displays the type of the response as never when I hover over it.
Am I doing something wrong here?