[英]inferring types from an Error throwing function in Typescript?
我在下面有一個 function ,它在調用doSomething()
之前檢查myValue
是否存在,如果不存在,它將拋出。 Typescript 接受這個...
function myFunction(){
if (!myValue) {
const error = Error(errorName);
error.name = errorName.replace(/\s+/g, "-").toLowerCase();
throw error;
}
const something = doSomething(myValue);
}
下面的實現使一個助手 Function 用於拋出一個命名的錯誤。 Typescript 不喜歡這樣,並且傳遞doSomething(myValue)
的錯誤myValue
可能是未定義的。 如何鍵入namedError
以便它具有從上面推斷的類型,它是真實的?
function myFunction(){
if (!myValue) {
namedError("my value doesn't exist");
}
const something = doSomething(myValue);
}
function namedError(errorName: string){
const error = Error(errorName);
error.name = errorName.replace(/\s+/g, "-").toLowerCase();
throw error;
};
從 typescript 3.7開始,返回的函數在控制流分析中的影響never
與throw
表達式相同。 所以這將起作用:
let myValue: string | undefined;
function myFunction() {
if (!myValue) {
namedError("my value doesn't exist");
}
const something = doSomething(myValue);
}
function namedError(errorName: string): never {
const error = Error(errorName);
error.name = errorName.replace(/\s+/g, "-").toLowerCase();
throw error;
};
function doSomething(value: string) {
}
Typescript null elimination doesn't work with nest function calls (unless it's an immediately invoked function expression) hence the error. 您可以將 doSomething 調用移動到 else 塊中,或者當您確定某個值不會是 null 或未定義時使用類型斷言運算符。
所以要么:
if (!myValue) {
namedError(...)
} else {
const something = doSomething(myValue);
}
或者
if (!myValue) {
namedError(...)
}
// use type assertion (! postfix) to tell compiler that the value will never be null or undefined
const something = doSomething(myValue!);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.