I have a fetch method that uses generic types and I pass it for example three types such as UserTokens | AuthError | AuthUnHandleError, but when I want to load a property of the returned function, it only lets me load a property that exists in all three types or interfaces, the others that are not the same in all the types cannot be loaded.
export const authApiRequestSender = async <S , F> (router: string, body: object, header: Header, method: Method): Promise<S | F | AuthUnHandleError> => {
try {
const request = await fetch(process.env.api_url + router, {
method: method,
mode: 'cors',
headers: { ...header, 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!request.ok) {
return getAuthError<F>(request);
} else {
return getAuthSuccessResponse<S>(request);
}
} catch (error) {
return createAuthUnhandledErrorObject(router)
}
};
And after that, I use it like this:
export const userTokens = async (accessToken: string): Promise<UserTokens | AuthError | AuthUnHandleError> => {
const response = await authApiRequestSender<UserTokens, AuthError>(
'/auth/v1/user-tokens',
{},
{
Authorization: `Bearer ${accessToken}`,
},
'POST'
);
return response;
};
And my types and interface
export type AuthError = {
status: number | string;
statusText: string;
url: string;
action: string;
message: string;
system: string;
errors: Array<any> | [];
}
export interface LoginOutPut {
status: string | number;
action: 'login' | 'register' | 'edit_profile';
auth: {
access_expires_in: number;
access_token: Token;
access_token_type: 'access';
refresh_expires_in: number;
refresh_token: Token;
refresh_token_type: 'refresh';
};
message: string;
system: 'user';
user_info: {
email: string;
full_name: string;
id: string;
status: string;
username: string;
};
errors?: any;
}
type AuthNormalOutPut = Omit<LoginOutPut, 'auth'>;
export interface UserTokens extends AuthNormalOutPut {
user_tokens_info: Array<{
access_expires_in: number;
create_time: number;
last_used: number;
os: string;
type: 'refresh' | 'access';
}>;
}
For example, I can not load user_tokens_info property because does not exist in all 3 types, there is one type has it.
Thank you in advance.