簡體   English   中英

TypeScript 與 Try/Catch 中的錯誤

[英]Errors in TypeScript vs. Try/Catch

我應該如何在 TypeScript 中使用Try/Catch 我不希望它檢查給定塊中的任何錯誤,因為我已經檢查了它們(錯誤是預期的,並且 state 由 catch 控制)。

我將代碼包裝在Try/Catch中(只是示例):

try {
    let data = localStorage.getItem('something');
    // Err. TS2345; I know, that's why you're in the try block
    data = JSON.parse(data);
    // Err. TS2531; I know, that's why you're in the try block
    data.exp = new Date(data.exp * 1000);
    return data;
} catch {
    return null;
}

TypeScript 拒絕編譯它。 有什么辦法可以告訴 TypeScript 我知道這個錯誤並且我可以接受嗎? 我不想在每一行都使用//@ts-ignore (假設我可以有更長的代碼)並且我不想關閉strict mode 有沒有更好的解決方案?

TypeScript 的目的是幫助您解決由類型問題引起的編碼錯誤。 它給你 TS2345 因為你正在傳遞string | null string | null into JSON.parse (which expects just string ), and it's giving you TS2531 and TS2339 because your code is using data as though it won't be null (but it may well be) and as though it has an exp property (which據 TypeScript 所知,它不知道)。

如果要禁用data類型檢查,請使用any類型

try {
    let data: any = localStorage.getItem('something');
//          ^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− here
    data = JSON.parse(data);
    data.exp = new Date(data.exp * 1000);
    return data;
} catch {
    return null;
}

從鏈接的文檔中:

any

TypeScript 也有一個特殊的類型, any ,您可以在不希望特定值導致類型檢查錯誤時使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM