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 errorInterface 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 typegaurd 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 typegaurd 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 Vscode displays the type of the response as never when I hover over it.
Am i doing something wrong here? Any help would be appreciated