首页 > 解决方案 > 如何在打字稿中声明 getAttribute 函数类型

问题描述

我正在使用带有 xpath 模块的nestjs 打字稿。
但是由于 @types/xpath 不存在 xpath 模块类型,所以我声明了我自己的 xpath 类型,如下所示。

import * as xpath from 'xpath';

export class XmlParserService {

  private query(q: string): Array<Node | string> {
    return xpath.useNamespaces(this.namespaces)(q, this.parsedXml);
  }

我在主目录中声明了 xpath 类型。

// ./src/@types/xpath/index.d.ts

declare module 'xpath' {
  type SelectedValue = Node | string;

  interface XPathSelect {
    (expression: string, node?: Node): Array<SelectedValue>;

    (expression: string, node: Node, single: true): SelectedValue | undefined;
  }

  export const select: XPathSelect;

  export function useNamespaces(namespaceMap: {
    [name: string]: string;
  }): XPathSelect;
}

当我使用这个查询函数时,它返回元素对象。
因此我可以使用 getAttribute 和 ownerDocument。
但是,它给出了打字稿错误。

错误:(104, 19) TS2339: 类型 'string | 上不存在属性 'ownerDocument' 节点'。“字符串”类型上不存在属性“ownerDocument”或“getAttribute”。

  const currentNode = this.query(currentNodeQuery)[0];
  
  const idAttribute = currentNode.getAttribute('ID') ? 'ID' : 'Id';

  const ownerD = currentNode.ownerDocument

我怎样才能为这种情况申报更多?感谢您阅读。

标签: javascriptnode.jstypescript

解决方案


推荐阅读