Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript indexer still getting tslint error "object access via string literals is disallowed"

I am trying to write type definitions for the xmldoc npm package.

So far I have this:

declare module 'xmldoc' {

   export class XmlDocument {
    constructor(contents: string);
    public children: IXmlNode[];
  }

  export interface IXmlNode {
    attr: IXmlAttributes;
    val: string;
    name: string;
    children: IXmlNode[];
  }

  export interface IXmlAttributes {
    [index: string]: string;
  }

}

tslint is still complaining at this code

  valueId = node.attr["id"];

with the error message object access via string literals is disallowed

I thought my indexer ([index: string]: string) worked around this.

Can anyone give me a clue as to why it isn't working?

like image 316
Andrew Murphy Avatar asked May 04 '16 13:05

Andrew Murphy


1 Answers

Your indexer does work around this, in that it allows TypeScript to compile it, and you're right that it's valid compiling TypeScript code.

The issue here is just the TSLint rule; while it's valid TypeScript, TSLint is trying to encourage you not to do it, because you're indexing by a constant string, so it could just be property on the object. TSLint thinks you should define fixed properties on IXMLAttributes for the properties you're going to access.

You could well do that; adding a 'id: string' property on your IXMLAttributes (in addition to the indexed property, if there is a non-constant case where you'd like to use that) isn't a bad idea.

Personally though I think this is just TSLint being a bit heavy-handed here. There's perfectly good reasons to use constant string indexing like this in these cases. I'd just turn off the no-string-literal rule in your TSLint config.

like image 199
Tim Perry Avatar answered Sep 27 '22 22:09

Tim Perry