node.js - 2つの異なるオブジェクトを返すTypeScript関数
私はTypeScriptにはかなり新しく、このことをどうやって動かすかを理解しようとしています。いくつか徹底的にグーグル検索をしましたが、最終的にはStack Overflowに頼ることにしました。
私は、ある条件に基づいて User オブジェクトまたは Error オブジェクトを返す関数を持っています。この関数を呼び出すと、次のエラーを回避せずに異なるケースを処理できないようです。
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...
}
}
何か見落としているのか、それともこういうことはそもそも不可能なのでしょうか?
回答 #1
次のように、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...
}
}
