为什么 tslint 在启用 no-unsafe-any 时将强类型参数的属性标记为 any
Why is tslint flagging properties of strongly typed parameters as any when no-unsafe-any is enabled
在我的 Angular 项目中启用 no-unsafe-any tslint 规则后,我开始看到很多结果。深入研究它们,将注入到构造函数的参数的属性标记为 any 类型,即使它们是强类型 类。我不明白为什么要标记这些,显然我在这里遗漏了一些简单的东西。
错误信息:
Unsafe use of expression of type 'any'.
示例组件:
@Component({..)}
export class SampleComponent {
private localString: string;
constructor(private injectedService: SampleService) {
this.localString= this.injectedService.stringProperty;
}
}
以及示例服务:
@Injectable({providedIn: 'root'})
export class SampleService {
public stringProperty: string;
}
注意:如果背景有用,请继续这个问题:
问题可能是很多 angular 装饰器没有实际的 return 类型,它们 return any
。 tslint 规则正确地识别出我们正在尝试将 any 分配给需要装饰器的地方。
一种解决方案是增加装饰器的类型。我在我的一个项目中激活了规则,这些增强让 linter 很开心,你可能需要根据需要添加其他的:
import { Type } from '@angular/core/src/type';
declare module '@angular/core/src/metadata/directives' {
export interface InputDecorator {
// tslint:disable-next-line:callable-types
(bindingPropertyName?: string): PropertyDecorator;
}
}
declare module '@angular/core/src/di/injectable' {
export interface InjectableDecorator {
(): ClassDecorator;
// tslint:disable-next-line:unified-signatures
(options?: {
providedIn: Type<any> | 'root' | null;
} & InjectableProvider): ClassDecorator;
}
}
在我的例子中,我只需要将表达式的一部分转换为数字
this.refundNegative = requestedAmount.value < 0;
变成了
this.refundNegative = requestedAmount.value as number < 0;
我的 linting 问题已经解决了。
在我的 Angular 项目中启用 no-unsafe-any tslint 规则后,我开始看到很多结果。深入研究它们,将注入到构造函数的参数的属性标记为 any 类型,即使它们是强类型 类。我不明白为什么要标记这些,显然我在这里遗漏了一些简单的东西。
错误信息:
Unsafe use of expression of type 'any'.
示例组件:
@Component({..)}
export class SampleComponent {
private localString: string;
constructor(private injectedService: SampleService) {
this.localString= this.injectedService.stringProperty;
}
}
以及示例服务:
@Injectable({providedIn: 'root'})
export class SampleService {
public stringProperty: string;
}
注意:如果背景有用,请继续这个问题:
问题可能是很多 angular 装饰器没有实际的 return 类型,它们 return any
。 tslint 规则正确地识别出我们正在尝试将 any 分配给需要装饰器的地方。
一种解决方案是增加装饰器的类型。我在我的一个项目中激活了规则,这些增强让 linter 很开心,你可能需要根据需要添加其他的:
import { Type } from '@angular/core/src/type';
declare module '@angular/core/src/metadata/directives' {
export interface InputDecorator {
// tslint:disable-next-line:callable-types
(bindingPropertyName?: string): PropertyDecorator;
}
}
declare module '@angular/core/src/di/injectable' {
export interface InjectableDecorator {
(): ClassDecorator;
// tslint:disable-next-line:unified-signatures
(options?: {
providedIn: Type<any> | 'root' | null;
} & InjectableProvider): ClassDecorator;
}
}
在我的例子中,我只需要将表达式的一部分转换为数字
this.refundNegative = requestedAmount.value < 0;
变成了
this.refundNegative = requestedAmount.value as number < 0;
我的 linting 问题已经解决了。