【问题标题】:Why is tslint flagging properties of strongly typed parameters as any when no-unsafe-any is enabled为什么启用 no-unsafe-any 时 tslint 将强类型参数的属性标记为 any
【发布时间】:2019-06-19 06:12:20
【问题描述】:

在我的 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

【问题讨论】:

  • 您在哪一行得到错误。使用您的代码,我实际上在SampleService 上遇到错误,但这是由于Injectable 出于某种原因返回any ..仅供参考@Input 也返回any
  • 行和列是构造函数中 this.injectedService.stringProperty 的开始。抱歉,示例代码可能无法编译,因为我需要将其匿名化,但看起来会发生在访问注入依赖项属性的任何地方。
  • 也许这篇文章会有所帮助:github.com/palantir/tslint/issues/2728 我认为问题出在角度定义中的any 上,票证中有关于如何扩充定义的建议
  • 在不改变 Angular 装饰器的默认定义(如可注入、输入等)的情况下,这条规则似乎是不可靠的。但至少了解它发生的原因是件好事。如果您想将其放入答案中,我可以标记为已接受。
  • 我在我的一个项目中激活了规则,并为角度类型添加了一些增强,它工作正常。我会尽快添加我的发现

标签: angular typescript tslint


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    this.refundNegative = requestedAmount.value < 0;
    

    成为

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

    我的 linting 问题解决了。

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 2020-08-17
      • 2019-03-15
      • 2019-02-22
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      相关资源
      最近更新 更多