I'm fairly new to TypeScript and I'm trying to work out how to get this thing working. I've done some extensive Googling but have finally resorted to Stack Overflow.
I have a function that returns a User Object or an Error Object, based upon some condition. When I call this function, I can't seem to handle the different cases without getting the follow error.
Property 'error' does not exist on type 'User | Error'.
Property 'error' does not exist on type 'User'.ts(2339)
Here is some code to demonstate my goal, the error occurs at the >>
in the main()
funciton.
interface User {
email: string;
username: string;
}
interface Error {
error: string;
code: number;
}
async function get_user_info(user_id: number): Promise<User | Error> {
const result = await db.get_user(user_id); // let's say this returns false if no user found..
if (result) {
const user: User = {
email: result.email,
username: result.username
}
return user;
} else {
const err: Error = {
error: "Failed to fetch user.",
code: 583
}
return err;
}
}
async function main() {
const res = await get_user_info(42);
>> if (res.error) {
// handle this...
} else {
// continue onwards...
}
}
Am I missing anything, or is this sort of thing just not possible?
Apply a type guard that tests if it is an User
or an Error
object by checking if the error
property exists:
async function main() {
const res = await get_user_info(42);
if ('error' in res) {
if (res.error) {
// handle this...
}
} else {
// continue onwards...
}
}