我正在使用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;
该问题的根源是给予error
(catchError
库函数)的处理程序的Rxjs参数具有any
类型。我理解error
可以是任何类型,所以假设它有任何属性定义是不安全的,但我首先在实际引用它们之前检查这些属性的存在,这对我来说似乎是安全的。
我可以/应该做些什么来说服linter / TypeScript编译器它是安全的并通过规则?
在Angular的情况下,错误应始终为HttpErrorResponse类型
catchError((error: HttpErrorResponse) => {
//...
}
也就是说,在你的代码中你会看到error.error
,它在any
中被定义为HttpErrorResponse
,因此你应该使用类型保护来检查并将它转换为Error对象。不需要定义Error
- 它应该由typescript基类型定义。
function isError(value: any | undefined): value is Error {
return error && ((error as Error).message !== undefined);
}
然后用它
const errorMessage = isError(error.error) ? error.error.message : error.statusText;
您有两个选择,当您知道error
总是具有特定类型时,您可以只注释该类型。如果你不能确定,你可以使用type guard。
输入注释
使用类型注释,您可以简单地告诉编译器,您希望error
属于某种类型。您可以使用此方法完全避免使用any
类型:
interface Error {
status: string,
statusText: string,
error: { message: string | undefined } | undefined;
}
catchError((error: Error | undefined) => {
//...
}
护卫
只要值可以是某种类型,您就可以使用类型保护,但不一定必须属于该类型。类型保护将检查类型,在以下块中,变量将是该检查类型:
function isError(value: any | undefined): value is Error {
return error && ((error as Error).status !== undefined);
}
catchError(error => {
if (isError(error)) {
//Inside this block, error will be of type Error
}
}