在我的 Angular 项目中启用了无不安全的任何 tslint 规则后,我开始看到很多结果。深入研究它们,它将注入到构造函数的参数的属性标记为任何类型,即使它们是强类型类。我不明白为什么这些被标记,我显然在这里错过了一些简单的东西。
错误信息:
不安全使用类型为"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;
}
注意:如果背景有任何用处,则从此问题开始:打字稿未强制执行或检查返回类型
问题可能是很多角度装饰器没有实际的返回类型,它们返回any
。tslint 规则正确地标识了我们试图将任何分配给需要装饰器的位置。
一种解决方案是增加装饰器的类型。我在我的一个项目中激活了规则,这些增强使 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 问题解决了。