代码之家  ›  专栏  ›  技术社区  ›  kentor

TSLint:Backbone get()在所属模型意义之外调用

  •  1
  • kentor  · 技术社区  · 8 年前

    我正在使用微软的 tslint-microsoft-contrib tslint配置,我真的很满意。然而,有一条规则提醒我注意我的代码。我不理解规则描述文本,也不知道如何更优雅地解决这个问题。

    [tslint]Backbone get()在所属模型之外调用: 这客户get('位置')(模型外未设置主干)

    代码:

    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满意。有人能告诉我这个规则意味着什么以及我如何解决它吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   kentor    8 年前

    我将引用哈姆雷特·DRC(来自微软团队)的话,他很好地解释了规则本身:

    在模型规则之外设置无主干的要点是 确保不会调用 编译器无法对强制执行正确性。例如,编译器将 如果你键入route,不要抱怨。参数。获取('id'), 路线参数。获取('ID'),路由。参数。获取('Id'),但只能获取其中一个 调用实际上会在运行时工作。设计建议是 在RouteParams上定义静态类型的“getId():number”方法 对象,以便编译器可以强制执行这些调用。因此,在我看来 规则实际上在您的代码中发现了一个您应该修复的问题(但是 见我的第二点:))

    资料来源: 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);
      }
    }
    
    推荐文章