如何重写代码以避免TSLint"通过字符串文字访问对象"

Den*_*lin 55 typescript tslint

我是TypeScript的新手,我想知道是否存在一种重写代码的好方法,以避免在以下代码中出现TSLint错误"不允许通过字符串文字进行对象访问"

interface ECType
{
    name: string;
    type: string;
    elementType?: string;
}

export var fields: { [structName: string]: Array<ECType>; } = { };

class ECStruct1 {
    foo: string;
    bar: number;
    baz: boolean;
    qux: number;
    quux: number;
    corge: ECStruct2[];
    grault: ECStruct2;

    constructor() {
        ...
    }
} 

fields['ECStruct1'] = [
    { name: 'foo', type: 'string' },
    { name: 'bar', type: 'int' },
    { name: 'baz', type: 'bool' },
    { name: 'qux', type: 'long' },
    { name: 'quux', type: 'ulong' },
    { name: 'corge', type: 'array', elementType: 'ECStruct2' },
    { name: 'grault', type: 'ECStruct2' }
];
Run Code Online (Sandbox Code Playgroud)

更新:最后,上面的内容将成为超过300 ECStruct秒的自生成文件的一部分,因此我希望将类定义(例如ECStruct1)后跟其元描述(例如fields['ECStruct1']).

JKi*_*ian 97

你有两个选择:

只需禁用该规则即可

/* tslint:disable:no-string-literal */
whatever.codeHere()
/* tslint:enable:no-string-literal */
Run Code Online (Sandbox Code Playgroud)

使用变量而不是字符串文字

// instead of 
fields['ECStruct1'] = ...
// do something like
let key = 'ECStruct1';
fields[key] = ...
Run Code Online (Sandbox Code Playgroud)

写/生成显式接口

请参阅MartylX上面的回答.实质上:

interface ECFieldList {
    ECStruct1: ECType[];
}

export var fields:ECFieldList = {
    ECStruct1: [
        ...
Run Code Online (Sandbox Code Playgroud)

其中任何一个都是合理的解决方案,虽然我不是#2的粉丝,因为它没有任何理由破坏你的代码.如果你正在生成代码,也许生成fields#3中的类型是一个很好的解决方案.


suh*_*lvs 25

您可以摆脱规则。在::中查找带有tslint.json的添加属性:"no-string-literal"falserules

{
"rules": {
    "no-string-literal": false,
    ... other rules ...
Run Code Online (Sandbox Code Playgroud)


小智 14

只需使用模板文字注释即可。

fields[`ECStruct1`]
Run Code Online (Sandbox Code Playgroud)

  • 丑陋的伎俩,因为它违背了警告的目的。但它以简单的方式解决了我的问题。 (6认同)

Mar*_*cka 6

这种方式呢?我不知道您是否需要索引器 ( [structName: string]: Array<ECType>;)。

interface ECType {
    name: string;
    type: string;
    elementType?: string;
}

interface ECFieldList {
    ECStruct1: ECType[];
}

export var fields:ECFieldList = {
    ECStruct1: [
        {name: 'foo', type: 'string'},
        {name: 'bar', type: 'int'},
        {name: 'baz', type: 'bool'},
        {name: 'qux', type: 'long'},
        {name: 'quux', type: 'ulong'},
        {name: 'corge', type: 'array', elementType: 'ECStruct2'},
        {name: 'grault', type: 'ECStruct2'}
    ]
};
Run Code Online (Sandbox Code Playgroud)


小智 5

可能不是最好的选择,但是使用

fields['ECStruct1'.toString()]
Run Code Online (Sandbox Code Playgroud)

也可以

  • 请不要这样做。linter 之所以存在,是因为设置该项目的人希望您遵循最佳代码实践,而不是绕过 linter 规则。 (3认同)