TypeScript: How to extend npm module type definitions?

The TypeScript Reference provides an example of merging declarations :

// observable.js
export class Observable<T> {
    // ... implementation left as an exercise for the reader ...
}

// map.ts
import { Observable } from "./observable";
declare module "./observable" {
    interface Observable<T> {
        map<U>(f: (x: T) => U): Observable<U>;
    }
}
Observable.prototype.map = function (f) {
    // ... another exercise for the reader
}

// consumer.ts
import { Observable } from "./observable";
import "./map";
let o: Observable<number>;
o.map(x => x.toFixed());

Since Webpack compiles my TypeScript code, I can use the npm xstream module that comes with this type definition:

import {Stream, MemoryStream, Listener, Producer, Operator} from './core';
export {Stream, MemoryStream, Listener, Producer, Operator};
export default Stream;

I can use it like this ( map- a valid method):

// consumer.ts
import { Stream } from "xstream";
let s: Stream<number>;
s.map(x => x);

I would like to expand the interface Streamand try something similar to the official example. Therefore, in my case, this is "xstream"instead "./observable", and my extensions are in the extensions.ts file instead of map.ts:

// extensions.ts
import { Stream } from "xstream";
declare module "xstream" {
  interface Stream<T> {
    foo(): Stream<T>;
  }
}

Stream.prototype.foo = function foo() {
  console.log('foo');
  return this;
};

// consumer.ts
import { Stream } from "xstream";
import "./extensions";
let s: Stream<number>;
s.foo().map(x => x);

Unfortunately, I get a few errors:

ERROR in [default] <path to my project>/node_modules/xstream/index.d.ts:2:9
Export declaration conflicts with exported declaration of 'Stream'

ERROR in [default] <path to my project>/src/extendingExistingModule/extensions.ts:8:0
Cannot find name 'Stream'.

ERROR in [default] <path to my project>/src/extendingExistingModule/index.ts:5:8
Property 'map' does not exist on type 'Stream<number>'.

How can I fix them?


used versions

typescript@2.0.0
xstream@5.3.2
+4

Source: https://habr.com/ru/post/1649325/


All Articles