在 TypeScript 手册中是声明合并的示例:
// 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());
由于 Webpack 编译了我的 TypeScript 代码,我可以使用 npm 模块xstream,它附带此类型定义:
import {Stream, MemoryStream, Listener, Producer, Operator} from './core';
export {Stream, MemoryStream, Listener, Producer, Operator};
export default Stream;
我可以这样使用它(map
是一种有效的方法):
// consumer.ts
import { Stream } from "xstream";
let s: Stream<number>;
s.map(x => x);
我想扩展Stream
接口并尝试类似于官方示例的东西。所以在我的情况下,它"xstream"
不是,"./observable"
我的扩展名在文件extensions.ts而不是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);
可悲的是,我收到多个错误:
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>'.
我该如何修复它们?
使用过的版本
typescript@2.0.0
xstream@5.3.2