我很難解決這個問題。
打字稿游樂場
為什么 Typescypt 只推斷出一些回傳型別(檢查操場)?我做錯了什么?
就我所見,這只發生在使用泛型時。
提前致謝!
uj5u.com熱心網友回復:
這不是忽略它們,只是CustomError<{}>足以覆寫字串和數字。兩者string和2都可以分配給 type {}。
// No errors with either of these
const test: {} = 'Test';
const test2: {} = 2;
所以 typescript 可以說回傳型別是CustomError<{}> | CustomError<null>,或者它是CustomError<{}> | CustomError<string> | CustomError<number> | CustomError<null>,但是由于兩者之間沒有區別,所以 typescript 使用較短的那個。
游樂場鏈接
如果將物件的大小寫更改為更復雜的物件,使得字串和數字不再匹配,那么您將看到數字和字串出現在回傳型別中:
if(this.randomOperation() == false){
return new CustomError({ hello: 'world });
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409696.html
標籤:
