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

问题描述 投票:34回答:4

我是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' }
];

更新:最后,上面的内容将是自我生成的文件的一部分,其中包含超过300个ECStructs,因此我希望有类定义(例如ECStruct1),然后是元描述(例如fields['ECStruct1'])。

typescript tslint
4个回答
84
投票

你有两个选择:

只需禁用该规则即可

/* tslint:disable:no-string-literal */
whatever.codeHere()
/* tslint:enable:no-string-literal */

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

// instead of 
fields['ECStruct1'] = ...
// do something like
let key = 'ECStruct1';
fields[key] = ...

写/生成显式接口

MartylX's answer above。实质上:

interface ECFieldList {
    ECStruct1: ECType[];
}

export var fields:ECFieldList = {
    ECStruct1: [
        ...

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


21
投票

你可以摆脱这条规则。在tslint.json寻找qazxsw poi,在qazxsw poi中添加属性qazxsw poi ::

"no-string-literal"

5
投票

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

false

也有效


3
投票

这个怎么样?我不知道你是否需要索引器(rules)。

{
"rules": {
    "no-string-literal": false,
    ... other rules ...

3
投票

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

fields['ECStruct1'.toString()]

0
投票

一种简单的方法是定义一个变量来保存ECStruct1的值:

[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'}
    ]
};
© www.soinside.com 2019 - 2024. All rights reserved.