【问题标题】:extend typing for nightmare为噩梦延长打字时间
【发布时间】:2019-02-20 08:42:52
【问题描述】:

我正在使用来自herenightmare 类的类型。这是通过 npm install @types/nightmare 安装的

我想在不修改 node_modules 中的 index.d.ts 的情况下扩展现有类型。特别是通过添加 action()evaluate_now() 方法。 action() 是一个静态方法。

这就是我所做的 我在我的项目根文件夹中创建了一个自定义类型文件

custom-typings.d.ts

declare namespace Nightmare {
  export class Nightmare {
    evaluate_now<T1, T2, R>(
      fn: (arg1: T1, done: T2) => R,
      done: T2,
      arg1: T1
    ): Nightmare;
    static action<T1, T2, R>(name: string, fn: (arg1: T1, done: T2) => R): void;
  }
}

在我的主应用程序文件中,我有以下内容

index.ts

/// <reference path='custom-typings.d.ts'/>

import Nightmare = require('nightmare');

function size(this: Nightmare, done: any) {
  this.evaluate_now(() => {
    const w = Math.max(
      document.documentElement.clientWidth,
      window.innerWidth || 0
    );
    const h = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    );
    return {
      height: h,
      width: w
    };
  }, done);
}

Nightmare.action('size', size);

// no errors here from the types declared by the @types in node_modules.
new Nightmare()
  .goto('http://yahoo.com')
  .type('input[title="Search"]', 'github nightmare')
  .click('.searchsubmit');

我收到以下错误

  • “Nightmare”类型上不存在属性“evaluate_now”。
  • “typeof Nightmare”类型上不存在属性“action”。

我正在使用 Typescript 3。看起来我的自定义类型没有被检测到。我一直在倾诉declaration merging documents,但我不知道我做错了什么。

谢谢

【问题讨论】:

    标签: node.js typescript typescript-typings nightmare


    【解决方案1】:

    您在custom-typings.d.ts 中声明的全局命名空间与模块无关。相反,您需要扩充模块:

    declare module "dummy" {
      module "nightmare" {
        // ...
      }
    }
    

    但是,Nightmare 类在原始类型 (export = Nightmare) 中是导出分配的,并且目前无法扩充 AFAIK 导出分配的类;见this previous answer。因此,您必须将修改后的 @types/nightmare 副本添加到您的项目中。

    【讨论】:

    • 谢谢马特。这不是关于默认导出类的问题,而不是使用export = 导出的类吗?
    • 对。我刚刚对该问题添加了一条评论,指出我相信导出分配的类也有同样的问题。我认为提交另一个问题不会有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 2020-03-14
    • 2010-11-13
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多