如何重写代码以避免 TSLint“通过字符串文字访问对象" [英] How to rewrite code to avoid TSLint "object access via string literals"
问题描述
我对 TypeScript 还很陌生,我想知道是否存在重写代码的好方法来避免以下代码中的 TSLint 错误不允许通过字符串文字访问对象"
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
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
s的自生成文件的一部分,所以我想要类定义(例如 ECStruct1
)后跟其元描述(例如 fields['ECStruct1']
).
Update: At the end the content above will be part of a self-generated file with more than 300 ECStruct
s, so I would like to have the class definition (e.g. ECStruct1
) followed by its meta-description (e.g. fields['ECStruct1']
).
推荐答案
这里有几个选项:
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) 编写/生成显式接口
请参阅以上MartylX 的回答.本质上:
interface ECFieldList {
ECStruct1: ECType[];
}
export var fields:ECFieldList = {
ECStruct1: [
...
这些都是合理的解决方案,尽管我不是 #2 的粉丝,因为它无缘无故地破坏了您的代码.如果您无论如何都要生成代码,也许像 #3 中那样为 fields
生成类型是一个很好的解决方案.
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 fields
as in #3 is a good solution.
这篇关于如何重写代码以避免 TSLint“通过字符串文字访问对象"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!