TypeScript indexer still gets tslint error "access to object through string literals is denied"

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 about this code

  valueId = node.attr["id"]; 

with error message object access via string literals is disallowed

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

Can someone let me know why it is not working?

+5
source share
1 answer

Your indexer wraps around this, so it allows TypeScript to compile it, and you're right that it really compiles TypeScript code.

The problem here is just the TSLint rule; while it is valid TypeScript, TSLint tries to encourage you not to do this because you are indexing a constant string, so this may just be a property of the object. TSLint thinks you should define fixed properties on IXMLAttributes for the properties you are about to access.

You could do it; adding the "id: string" property to your IXMLAttributes (in addition to the indexed property, if there is a fickle case when you want to use it) is not a bad idea.

Personally, although I think it's just TSLint, here is a little tough. In these cases, there are good reasons to use constant row indexing. I would just disable the no-string-literal rule in your TSLint configuration.

+5
source

All Articles