Declaration Merging機能を試すため、
jestのテスト環境で以下のコードを書きました。
import 'rxjs'; import { Observable } from 'rxjs/Observable'; export function hello <T>(this: Observable<T> ): Observable<T> { console.log('hello'); return this; } Observable.prototype.hello = hello; declare module 'rxjs/Observable' { // tslint:disable-next-line:no-shadowed-variable interface Observable<T> { hello: typeof hello; } } describe('main test', () => { it('test 01', () => { Observable.of(1, 2, 3, 4, 5) .hello() .map(x => x) .subscribe(x => (console.log(x))); }); });
sampleとしてObservable<T> にhello
メソッドを追加しただけです。
これはモジュール拡張として動作します。
そこで拡張部分をnpmモジュールとして分離しました。
そのモジュールは以下においています
https://github.com/m0a/hello-observable
上記モジュールをnpm link
コマンドでローカルで使えるようにします。
以下のように呼び出してみます。
import { Observable } from 'rxjs/Observable'; import 'rxjs'; import 'hello-observable'; describe('main test', () => { it('test 01', () => { Observable.of(1, 2, 3, 4, 5) .hello() // error .map(x => x) .subscribe(x => (console.log(x))); }); });
以下のようなエラーメッセージが出ます。
file: 'file:///Users/m0a/repo/github.com/m0a/declaration-merging-test/src/__test__/main.test.ts' severity: 'エラー' message: 'Property 'hello' does not exist on type 'Observable<number>'.' at: '8,14' source: 'ts'
Declaration Merging機能をnpm外部モジュールから使う方法を教えて下さい
なお、参考になるかわかりませんが
生成されたd.tsと.jsファイルは以下となります。
- lib/index.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Observable_1 = require("rxjs/Observable"); function hello() { console.log('hello'); return this; } exports.hello = hello; Observable_1.Observable.prototype.hello = hello;
- lib/index.d.ts
import { Observable } from 'rxjs/Observable'; export declare function hello<T>(this: Observable<T>): Observable<T>; declare module 'rxjs/Observable' { interface Observable<T> { hello: typeof hello; } }
あなたの回答
tips
プレビュー