我是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个ECStruct
s,因此我希望有类定义(例如ECStruct1
),然后是元描述(例如fields['ECStruct1']
)。
你有两个选择:
只需禁用该规则即可
/* 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
生成一个类型是一个很好的解决方案。
你可以摆脱这条规则。在tslint.json
寻找qazxsw poi,在qazxsw poi中添加属性qazxsw poi ::
"no-string-literal"
可能不是最好的选择,但使用
false
也有效
这个怎么样?我不知道你是否需要索引器(rules
)。
{
"rules": {
"no-string-literal": false,
... other rules ...
只需使用模板文字注释即可。
fields['ECStruct1'.toString()]
一种简单的方法是定义一个变量来保存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'}
]
};