当启用了no-unsafe-any时,为什么强类型参数的tslint标记属性为any

问题描述 投票:1回答:2
在我的Angular项目中

启用了no-unsafe-any 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;
}

注意:如果背景有任何用处,可从以下问题开始进行:Typescript not enforcing or checking return type

angular typescript tslint
2个回答
1
投票

问题可能是很多角度装饰器没有实际的返回类型,它们返回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;
    }
}

0
投票

就我而言,我只需要将表达式的一部分转换为数字

this.refundNegative = requestedAmount.value < 0;

成为

this.refundNegative = requestedAmount.value as number < 0;

我的棉绒问题解决了。

© www.soinside.com 2019 - 2024. All rights reserved.