I created a function that authorizes a user, which can return either a User object or a ResponseError
Here is my function:
async loginUser ({ commit }, data) {
try {
const user = await loginUser(data)
commit('setUser', user)
return user
} catch (e) {
return {
status: e.response.status,
errors: e.response.data.errors
}
}
}
Defined Types:
export interface User {
id?: number
}
export interface ErrorResponse {
status: number
errors: object
}
export interface Actions {
loginUser({ commit }: { commit: Commit }, data: LoginData): Promise<User | ErrorResponse>
}
And I use this function in my component as follows:
const res = await this.$store.dispatch('loginUser', {
email: this.formData.email,
password: this.formData.password
})
redirect(res, 'dashboard')
After the request, I need to check if an Error or User was returned (in the redirect function):
const redirect = (res: User | ErrorResponse, redirectTo: string) => {
if (res.id) {
router.push({ name: redirectTo })
} else {
ElMessage.error('Oops, there was an error.')
}
}
However, TypeScript shows me an error stating:
Property 'id' does not exist on type 'User | ErrorResponse'.Property 'id' does not exist on type 'ErrorResponse'.
I understand why this error occurs, but I'm unsure how to fix it. Any suggestions?