简体   繁体   中英

Typescript Node.js Prototype Won't Compile

I can't seem to figure out what I'm doing wrong here. I'd like to extend my Firebase object with a prototype method

However I get:

Property 'foo' does not exist on type 'Firebase'

/// <reference path="./tsd.d.ts"/>
import Firebase = require('firebase');
interface Firebase {
     foo : () => string
}

Firebase.prototype.foo = function(): string {
    return "foo";
}

var myRootRef = new Firebase('myUrl');
firebase.foo() // property 'foo' does not exist on type 'Firebase'.

Since you have an import in your code :

import Firebase = require('firebase');

your file is now a module and the interface Firebase { is disconnected from the global namespace. Move this declaration into a global.d.ts file.

More : see modifying native types : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html

I actually solved it. I realized that I needed to declare in a custom.d.ts that Firebase.

/// <reference path="../firebase/firebase.d.ts"/>
/// <reference path="../rx/rx.d.ts"/>
/// <reference path="../rx/rx-lite.d.ts"/>

interface Firebase {
     rx_observe : (eventType: string) => Rx.Observable<FirebaseDataSnapshot>
}

declare var fb : Firebase

declare module 'custom' {
     export = fb
}

Now I include my prototype declaration.

import Firebase = require('firebase');
import Rx = require('rx');

Firebase.prototype.__proto__.rx_observe = function(eventType: string): Rx.Observable<FirebaseDataSnapshot> {
    var self: Firebase = this;
    return Rx.Observable.create<FirebaseDataSnapshot>(observer => {
        var listener = self.on(eventType, (snapshot) => {
             observer.onNext(snapshot);
        })
        return () => {
            self.off(eventType, listener);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM