我对 TypeScript 还很陌生,我正在尝试弄清楚如何让这个东西发挥作用。 我进行了一些广泛的谷歌搜索,但最终求助于 Stack Overflow。
我有一个函数,它根据某些条件返回用户对象或错误对象。 当我调用这个函数时,我似乎无法在不出现以下错误的情况下处理不同的情况。
Property 'error' does not exist on type 'User | Error'.
Property 'error' does not exist on type 'User'.ts(2339)
这里有一些代码来演示我的目标,错误发生在 main()
函数中的 >>
处。
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...
}
}
我错过了什么,还是这种事情根本不可能?
最佳答案
应用类型保护,通过检查 error
属性是否存在来测试它是 User
还是 Error
对象:
async function main() {
const res = await get_user_info(42);
if ('error' in res) {
if (res.error) {
// handle this...
}
} else {
// continue onwards...
}
}
关于node.js - Typescript 函数返回两个不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59703856/