how to properly compare enums and interface unions?

I have the following function in my api client:
public static async getLoggedInUser(): Promise<IxUser | IxApiException> {
const res = await fetch(`${this.BASE_URL}/me`, {})

if (res.ok) {
return await res.json()
} else {
switch (res.status) {
case 401: {
return IxApiException.NOT_AUTHENTICATED;
}
default: {
return IxApiException.UNKNOWN;
}
}
}
}
public static async getLoggedInUser(): Promise<IxUser | IxApiException> {
const res = await fetch(`${this.BASE_URL}/me`, {})

if (res.ok) {
return await res.json()
} else {
switch (res.status) {
case 401: {
return IxApiException.NOT_AUTHENTICATED;
}
default: {
return IxApiException.UNKNOWN;
}
}
}
}
I now need to use it in my react component:
const query = useQuery({
queryKey: [],
queryFn: IxApiClient.getLoggedInUser
})
const query = useQuery({
queryKey: [],
queryFn: IxApiClient.getLoggedInUser
})
Here query.value will be a union of IxUser | IxApiException How can I check for the type and conditionally render something in react? I can't use instanceOf either on IxUser (because it's an interface) or IxApiException 'cause it's an enum:
export interface IxUser {
id: string,
email: string,
creation_timestamp: number,
creation_source: UserCreationSource
}

export enum IxApiException {
UNKNOWN = "Something went wrong, please try again later",
NOT_AUTHENTICATED = "You are not logged in",

REGISTER_INVALID_EMAIL_OR_PASSWORD = "The email or password are not valid",
REGISTER_UNUSABLE_EMAIL = "This email cannot be used to register",

LOGIN_INVALID_CREDENTIALS = "Email or password are incorrect",
LOGIN_EMAIL_NOT_VERIFIED = "You must verify your email to login",

EMAILS_RATE_LIMITED = "You requested too many emails, try again later",

PASSWORD_RESET_USER_NOT_FOUND = "No user with the provided email has been found"
}
export interface IxUser {
id: string,
email: string,
creation_timestamp: number,
creation_source: UserCreationSource
}

export enum IxApiException {
UNKNOWN = "Something went wrong, please try again later",
NOT_AUTHENTICATED = "You are not logged in",

REGISTER_INVALID_EMAIL_OR_PASSWORD = "The email or password are not valid",
REGISTER_UNUSABLE_EMAIL = "This email cannot be used to register",

LOGIN_INVALID_CREDENTIALS = "Email or password are incorrect",
LOGIN_EMAIL_NOT_VERIFIED = "You must verify your email to login",

EMAILS_RATE_LIMITED = "You requested too many emails, try again later",

PASSWORD_RESET_USER_NOT_FOUND = "No user with the provided email has been found"
}
Am I approaching this whole typing thing wrongly in typescript? Coming from different languages this is how I would usually structure things but here it seems really hard to use those types
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server