2017-12-03 116 views
0

我使用的是微軟的tslint-microsoft-contrib tslint配置,我對此非常滿意。然而,有一條規則警告我我的代碼。我不明白規則描述文字或我如何解決這個更優雅。TSLint:Backbone get()在擁有模型之外調用,意思是

[tslint]骨幹get()方法被稱爲擁有模型之外: this.client.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')

問題:

本來我面臨這個問題在我的項目不同的地方,我想我應該寫與類型定義的包裝方法,但我沒能做出tslint滿意,要麼。有人能夠啓發我這個規則的意義和我如何解決它嗎?

回答

0

我引用HamletDRC(從Microsoft隊)誰解釋規則本身非常好:

無骨幹-GET-設置外模型規則的要點是使 確定您不會調用 編譯器無法強制執行的動態調度方法。例如,如果您輸入route.params.get('id'), route.params.get('ID'),route.params.get('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); 
    } 
} 
相關問題