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

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

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

You have a couple options here:

1) Just disable the rule

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

2) Use a variable instead of a string literal

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

3) Write/Generate an explicit interface

See MartylX's answer above. Essentially:

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 fields as in #3 is a good solution.


Just use template literal annotation.

fields[`ECStruct1`]