我正在尝试为xmldoc
npm包编写类型定义。
到目前为止,我有这个:
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仍然在抱怨这个代码
valueId = node.attr["id"];
带有错误消息object access via string literals is disallowed
我认为我的索引器([index: string]: string
)可以解决这个问题。
有人能告诉我为什么它不起作用吗?
您的索引器确实可以解决这个问题,因为它允许TypeScript对其进行编译,并且您认为它是有效的编译TypeScript代码。
这里的问题只是TSLint规则;虽然它是有效的TypeScript,但TSLint试图鼓励你不要这样做,因为你是通过一个常量字符串进行索引的,所以它可能只是对象的属性。TSLint认为应该在IXMLAttributes上为要访问的属性定义固定属性。
你完全可以那样做;在您的IXMLAttributes上添加一个"id:string"属性(除了索引属性之外,如果有一个非常量的情况,您想使用它)并不是一个坏主意。
就我个人而言,我认为这只是TSLint在这里有点强硬。在这些情况下,有充分的理由使用这样的常量字符串索引。我只想关闭TSLint配置中的无字符串文字规则。