在TypeScript手册中,这是declaration merging:
的示例// 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,它带有this类型定义:
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