首页 > 解决方案 > 为噩梦延长打字时间

问题描述

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

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

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

自定义类型.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;
  }
}

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

索引.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');

我收到以下错误

我正在使用 Typescript 3。看起来我的自定义类型没有被检测到。我一直在翻阅声明合并文件,但我不知道我做错了什么。

谢谢

标签: node.jstypescripttypescript-typingsnightmare

解决方案


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

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

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


推荐阅读