由于某種原因,打字稿無法確定代碼在運行時不可訪問,并顯示不可能發生的錯誤。
我有這樣的代碼:
實體
class ApplicationError extends Error {}
class Company {
public ownerId: number = 123;
}
// This is a mock to avoid business logic in example
function getCompany() {
return Math.random() ? new Company() : null;
}
class Logger {
private logAndThrow(method: 'error' | 'warning' | 'info' | 'debug', messageOrError: string | ApplicationError) {
if (typeof messageOrError === 'string') {
// ...
console.log(this);
return;
}
throw messageOrError;
}
public debug(message: string): void;
public debug(error: ApplicationError): never;
public debug(messageOrError: string | ApplicationError) {
this.logAndThrow('debug', messageOrError);
}
}
const logger = new Logger();
const company = getCompany();
logger.debug(new ApplicationError());
if (company.ownerId === 123) {
// ...
}
為什么 Typescript 在最后一行顯示錯誤TS2531: Object is possibly 'null'.?
uj5u.com熱心網友回復:
TypeScript 3.7在控制流分析和可達性方面引入了對像行內一樣處理never回傳函式的支持。throw在此之前,無法獲得您正在尋找的行為。這是在microsoft/TypeScript#32695中實作的,目的是使斷言函式起作用。
對于斷言函式和never回傳函式,此行為僅在函式具有顯式型別注釋時才有效,因此“潛在斷言呼叫的控制流分析不會回圈觸發進一步分析”(有關更多資訊,請參見microsoft/TypeScript#45385資訊)。觀察:
const assertsAnnotated: (x: any) => asserts x is string = () => { };
declare const x: unknown;
assertsAnnotated(x);
x.toString(); // okay
const assertsUnannotated = assertsAnnotated;
declare const y: unknown;
assertsUnannotated(y); // error,
// Assertions require every name in the call target
// to be declared with an explicit type annotation
y.toString(); // error, unknown
const throwsAnnotated: () => never = () => { throw new Error(); }
const throwsUnannotated = neverAnnotated;
if (Math.random() < 0.5) {
throwsAnnotated();
console.log("abc"); // error, unreachable
} else {
throwsUnannotated();
console.log("abc"); // no error
}
assertsAnnotated和都throwsAnnotated以所需的方式影響控制流,因為它們是顯式注釋的(請注意,函式陳述句也算作顯式注釋),而assertsUnannotated和throwsUnannotated則不是,因為它們的型別是推斷的。
even 會導致編譯器assertsUnannotated()錯誤,警告您asserts沒有效果;這是在microsoft/TypeScript#33622中實作的。最初這個錯誤也會發出警告throwsUnannotated,但該功能已根據此評論洗掉。因此never,如果函式未明確注釋,則 -returning 函式將默默地無法影響可達性。
這就是此代碼不影響可達性的原因:
const logger = new Logger();
logger.debug(new ApplicationError());
console.log("apparently reachable"); // no error here
-never回傳函式是logger.debug,但是 的型別logger由賦值推斷為。LoggerSologger.debug的型別沒有明確注釋,因此沒有特殊的控制流分析發生(也沒有錯誤警告您)。
這里的解決方法/修復是顯式注釋logger:
const logger: Logger = new Logger();
logger.debug(new ApplicationError());
console.log("apparently reachable"); // error! unreachable code
游樂場代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537358.html
標籤:打字稿例外扔打字稿-从不
上一篇:Python查詢-陣列
