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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33387090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:48:25  来源:igfitidea点击:

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

typescripttslint

提问by Denis Cappellin

I'm pretty new to TypeScript and I would like to know if there exists a good way to rewrite code to avoid TSLint error "object access via string literals is disallowed" in the following code

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

Update: At the end the content above will be part of a self-generated file with more than 300 ECStructs, so I would like to have the class definition (e.g. ECStruct1) followed by its meta-description (e.g. fields['ECStruct1']).

更新:最后,上面的内容将是一个超过 300ECStruct秒的自生成文件的一部分,所以我想要类定义(例如ECStruct1),然后是它的元描述(例如fields['ECStruct1'])。

回答by JKillian

You have a couple options here:

你有几个选择:

Just disable the rule

只需禁用规则

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

Use a variable instead of a string literal

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

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

Write/Generate an explicit interface

编写/生成显式接口

See MartylX's answer above. Essentially:

请参阅上面 MartylX 的回答。本质上:

interface ECFieldList {
    ECStruct1: ECType[];
}

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


Any of these are reasonable solutions, although I'm not as much of a fan of #2 because it's mangling up your code for no good reason. If you're generating code anyways, perhaps generating a type for fieldsas in #3 is a good solution.

这些中的任何一个都是合理的解决方案,尽管我不是 #2 的粉丝,因为它无缘无故地破坏了您的代码。如果您无论如何都在生成代码,fields那么在 #3 中生成一个类型可能是一个很好的解决方案。

回答by suhailvs

You can get rid of the rule. Look for tslint.json, the add a property "no-string-literal"with false, in rules::

你可以摆脱规则。寻找,在:: 中tslint.json添加一个"no-string-literal"带有false,的属性rules

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

回答by nyc_coder

Just use template literal annotation.

只需使用模板文字注释。

fields[`ECStruct1`]

回答by Martin Vseticka

What about this way? I don't know if you need the indexer ([structName: string]: Array<ECType>;) or not.

这种方式呢?我不知道您是否需要索引器 ( [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'}
    ]
};

回答by Vipkry

Probably not the best option, but using

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

fields['ECStruct1'.toString()]

works too

也能用

回答by Alex Trn

A simple way is to define a variable to hold the value of ECStruct1:

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

const sampleName = 'ECStruct1';

and then, get access to the object by using the variable as index:

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

fields[sampleName] ...