【问题标题】:TSLint: Backbone get() called outside of owning model meaningTSLint:在拥有模型含义之外调用主干 get()
【发布时间】:2018-05-16 19:30:21
【问题描述】:

我正在使用 Microsoft 的 tslint-microsoft-contrib tslint 配置,我对此非常满意。但是,有一条规则会警告我有关我的代码。我不明白规则描述文本或如何更优雅地解决这个问题。

[tslint] 在拥有模型之外调用主干 get(): this.client.get('locations') (no-backbone-get-set-outside-model)

代码:

import * as Redis from 'ioredis';
import config from './config';

export class RedisWrapper {
  private client: Redis.Redis

  constructor(redisUrl: string) {
    this.client = new Redis(redisUrl)
  }

  public async getLocations(): ILocation[] {
    const locationsResponse: string = await this.client.get('locations')
  }
}

在这一行中弹出 tslint 警告:const locationsResponse: string = await this.client.get('locations')

问题:

最初我在项目的另一个地方遇到了这个问题,我认为我应该用 typedef 编写包装器方法,但我也无法让 tslint 对此感到满意。有人能告诉我这条规则的含义以及我该如何解决它吗?

【问题讨论】:

    标签: node.js typescript tslint


    【解决方案1】:

    我将引用 HamletDRC(来自 Microsoft 团队),他很好地解释了规则本身:

    no-backbone-get-set-outside-model 规则的要点是使 确保您不调用动态调度的方法 编译器无法强制执行正确性。例如,编译器将 如果您输入 route.params.get('id'),请不要抱怨, route.params.get('ID'), route.params.get('Id') 但只有其中之一 调用实际上将在运行时工作。设计建议是 在 RouteParams 上定义一个静态类型的“getId(): number”方法 对象,以便编译器可以强制执行这些调用。所以,在我看来 rule 实际上在你的代码中发现了一个你应该修复的问题(但是 看我的第二点:))

    来源:https://github.com/Microsoft/tslint-microsoft-contrib/issues/123

    在这种特定情况下,可以像这样扩展 Redis 类:

    export class RedisWrapper extends Redis {
      public async getLocations(): Promise<ILocation[]> {
        const response: string = await this.get('locations');
        if (response == null || response.length === 0) { return []; }
    
        return <ILocation[]>JSON.parse(response);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多