如何重写代码以避免 TSLint "object access via string literals"

How to rewrite code to avoid TSLint "object access via string literals"

我是 TypeScript 的新手,我想知道是否存在重写代码以避免以下代码中的 TSLint 错误"object access via string literals is disallowed"的好方法

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多ECStruct的自生成文件的一部分,所以我想把class 定义(例如 ECStruct1)后跟其元描述(例如 fields['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'}
    ]
};

这里有几个选项:

1) 只需禁用规则

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

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

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

3) Write/Generate 显式接口

参见 。本质上:

interface ECFieldList {
    ECStruct1: ECType[];
}

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

这些都是合理的解决方案,尽管我不太喜欢 #2,因为它无缘无故地破坏了您的代码。如果您无论如何都要生成代码,也许像 #3 中那样为 fields 生成一个类型是一个很好的解决方案。

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

fields['ECStruct1'.toString()]

也有效

你可以去掉这个规则。寻找 tslint.json,在 rules::

中添加 属性 "no-string-literal"false
{
"rules": {
    "no-string-literal": false,
    ... other rules ...

只需使用模板文字注释。

fields[`ECStruct1`]

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

const sampleName = 'ECStruct1';

然后,通过使用变量作为索引来访问对象:

fields[sampleName] ...

我遇到了同样的错误。但我尝试使用 type of Headers of Request 对象,它对我有用。以下是我设法解决问题的方法。

const objToAdd: { [key: string]: string } = {};
objToAdd.type = 'typeToAdd';
objToAdd.key = 'keyToAdd';
objToAdd.value = 'valueToAdd';

如果您看到 { [key: string]: string } 类型,则告诉 TSLint 该对象采用字符串类型的键和值。 同样,{ [key: string]: any } 类型指定键是 string 类型,值是 any 类型