thitemple
thitemple

Reputation: 6059

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

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. 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.

What's wrong with that definition?

Upvotes: 6

Views: 1023

Answers (1)

Frank Tan
Frank Tan

Reputation: 4412

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.

I'm guessing that you installed sinon via typings install sinon. If you do typings search sinon there are actually 2, one from npm and one from dt. The default installs the npm definitions. This is what the dt definition looks like:

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:

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.
  2. Install the DefinitelyTyped typings for sinon: typings install sinon --source dt --global
  3. Install the DefinitelyTyped typings for sinon-stub-promise: typings 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();

Upvotes: 1

Related Questions