【发布时间】:2019-02-22 06:48:46
【问题描述】:
我正在使用 TSLint 来检查我的 Angular TypeScript 代码。我启用了no-unsafe-any 规则,因为对我来说,永远不要假设any 类型的属性是一个很好的规则。
问题是该规则在我的某些代码上报告了错误,除了禁用该规则之外,我无法以任何方式修复这些错误。根据以下规则无效的代码示例。
public intercept(request: HttpRequest<{}>, next: HttpHandler): Observable<HttpEvent<{}>> {
return next
.handle(request)
.pipe(
catchError(error => {
if (error && error.status === httpCodeUnauthorized) {
// Auto logout if unathorized
this.authenticationService.logout();
}
const errorMessage = (error.error && error.error.message) || error.statusText;
return throwError(errorMessage);
}),
);
}
Linter 在 2 行报告 4 个错误:
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[24, 24]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 33]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 48]: Unsafe use of expression of type 'any'.
ERROR: /home/robert/programming/npc/gui/src/app/core/authentication/unauthorized.interceptor.ts[29, 72]: Unsafe use of expression of type 'any'
2 个有问题的行是:
if (error && error.status === httpCodeUnauthorized) {const errorMessage = (error.error && error.error.message) || error.statusText;
问题的根源在于catchError(Rxjs 库函数)的处理程序的error 参数具有any 类型。我知道error 可以是任何类型,因此假设它定义了任何属性是不安全的,但我会在实际引用它们之前首先检查这些属性是否存在,这对我来说似乎是安全的。
我可以/应该做什么来让 linter/TypeScript 编译器相信它是安全的并通过规则?
【问题讨论】:
-
如果你只是把这行换成
if (error) { ... },问题会持续吗? -
@Cerberus 不幸的是,它仍然报告 4 个错误。
标签: typescript tslint typescript-types