TypeScript - 如何重寫程式碼以避免 TSLint「透過字串字面值存取物件」
我對 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,因此我希望有類別定義(例如 ECStruct1)緊跟其元描述(例如 fields['ECStruct1'])。
答案#1
你在這裡有幾個選擇:
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生成一個類型是一個不錯的解決方案。
答案#2
你可以取消這個規則。尋找 tslint.json,然後在 rules 中添加屬性 "no-string-literal" 並設為 false:
{
"rules": {
"no-string-literal": false,
... other rules ...
答案#3
只使用模板字面量註解。
fields[`ECStruct1`]
