對于打字稿來說相對較新,我遇到了一個我在第一個專案中沒有遇到的問題 - 在try-catch 中的 api 請求之前宣告變數時,似乎會在之后對該變數的操作拋出打字稿錯誤試著抓。
我撰寫了示例代碼來顯示下面的問題。
是有問題的res變數,位于 if 陳述句的頂部。
interface AuthApiData {
message: string;
success: boolean;
}
interface AuthApiRes {
status: number;
data: AuthApiData;
}
if (router.pathname !== '/login') {
let res: AuthApiRes;
let status;
const authenticate = async () => {
try {
res = await axiosPrivate.get('/api/gilat');
status = res?.status;
} catch (err) {
console.log('authflow err:', err);
}
};
authenticate();
if (status === 200 && res?.data?.success === true) {
// I wanted to continue writing code here
}
}
如果有人想查看打字稿在哪里拋出錯誤以及工具提示上出現的錯誤,我已將影像放在問題的底部。
All the code does here is declare a variable res before a try-catch statement, then try to use this variable in an if-statement after. Inside the try-catch there is an api request that sets the result to this res variable when the asynchronous request is resolved.
If I declare res to be some initial object befitting of the it's interface the error goes away, e.g. res = { status: 403, data: ... }.
I also tried initializing its type with:
let res = AuthApiRes | undefined
Which fixes the problem but I find it messy or rather I'm unsure if this is just "cheating" typescript.
I don't wish to initialize this variable into this an empty placeholder object, but rather for it to remain unassigned until the api resolves.
這是否可能,如果不是,我如何在不初始化變數或設定聯合“或”未定義的情況下洗掉此錯誤,因為它在宣告期間鍵入?

uj5u.com熱心網友回復:
我還嘗試使用以下方法初始化其型別:
let res: AuthApiRes | undefined這解決了問題,但我發現它很亂,或者我不確定 > 這是否只是“作弊”打字稿。
當一個變數被宣告但未初始化時,它的值為,因為當你添加聯合undefined時,這個打字稿不會抱怨。undefined
對我來說,最好的方法是初始化res為null,然后檢查它:
let res: AuthApiRes | null = null;
if(res) {
if(status === 200 && res.data?.success === true) {
...
}
}
與status變數相同。
如果你不喜歡這種方法,你可以res加上前綴!
let res!: AuthApiRes
這提示您實際上會為 typescript 賦值?es,但是您將丟失 typescript 檢查,對我來說,這是不值得的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450784.html
