简体   繁体   English

扩充TypeScript模块

[英]Augmenting a TypeScript Module

I'm trying to augment the Sinon type definition for our project, here's how the Sinon.d.ts is defined 我正在尝试为我们的项目增加Sinon类型定义,这里是Sinon.d.ts的定义方式

declare module 'sinon' {
  module Sinon {
    interface SinonStub extends SinonSpy {
      ...
    }
    interface SinonStatic { ... }
    ...
  }

  var Sinon: Sinon.SinonStatic;

  export = Sinon;
}

I have a definitions.d.ts which I use in my project for any custom definitions. 我有一个definitions.d.ts ,我在我的项目中用于任何自定义定义。 Here's how I tried to do it: 这是我试图这样做的方式:

declare module 'sinon' {
  module Sinon {
    interface SinonPromise {
      resolves(value?: any): void;
      rejects(value?: any): void;
    }

    interface SinonStub {
      returnsPromise(): SinonPromise;
    }
  }
}

But the compiler does not recognize the new returnsPromise in the SinonStub interface, nor does it recognize the new SinonPromise type. 但是编译器无法识别新returnsPromiseSinonStub接口,也不承认新SinonPromise类型。

What's wrong with that definition? 这个定义有什么问题?

I believe your case requires a workaround. 我相信你的情况需要一个解决方法。 The definition file you have does not export any type definitions, so they can't be extended outside of that file. 您拥有的定义文件不会export任何类型定义,因此无法将其扩展到该文件之外。

I'm guessing that you installed sinon via typings install sinon . 我猜你安装sinon通过typings install sinon If you do typings search sinon there are actually 2, one from npm and one from dt . 如果你做类型typings search sinon实际上有2个,一个来自npm ,一个来自dt The default installs the npm definitions. 默认安装npm定义。 This is what the dt definition looks like: 这就是dt定义的样子:

declare namespace Sinon {
  // ...
  interface SinonStub extends SinonSpy {
    // ...
  }
  // ...
}

declare var sinon: Sinon.SinonStatic;

declare module "sinon" {
  export = sinon;
}

There is also a dt entry for sinon-stub-promise , which plays nicely with the above: 还有一个sinon-stub-promisedt条目,与上面的内容很好地配合:

declare namespace Sinon {
  interface SinonPromise {
    resolves(value?: any): void;
    rejects(value?: any): void;
  }

  interface SinonStub {
    returnsPromise(): SinonPromise;
  }
}

So, this is the workaround: 所以,这是解决方法:

  1. Remove the current sinon typing. 删除当前的sinon输入。
  2. Install the DefinitelyTyped typings for sinon : typings install sinon --source dt --global sinon安装DefinitelyTyped sinontypings install sinon --source dt --global
  3. Install the DefinitelyTyped typings for sinon-stub-promise : typings install sinon-stub-promise --source dt --global sinon-stub-promise typings install sinon-stub-promise --source dt --globaltypings install sinon-stub-promise --source dt --global

This now successfully compiles: 现在成功编译:

/// <reference path="typings/index.d.ts" />

import * as sinon from 'sinon';

sinon.stub().returnsPromise();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM