Amitabh
Amitabh

Reputation: 61187

TypeScript: How to inherit from javascript constructor function?

How can I inherit from a constructor function in javascript?

e.g. I have a base class written in native js

var MyModule;
(function (MyModule) {
    var MyBase = (function () {

        function MyBase(container, $MyElement) {

            this._container = container;
            this._$MyElement = $MyElement;
        }


        MyBase.prototype.toString = function () {
            return this._previewType;
        };

        MyBase.prototype.method1 = function(){

        };

        MyBase.prototype.method2 = function () {
            return this._isPreviewAffected;
        };



        return MyBase;
    })();
    MyModule.MyBase = MyBase;    
})(MyModule || (MyModule = {}));

How do I inherit it in typescript. I tried following code. I get the error "Incorrect reference: referenced file: "my-base.js" cannot be resolved"

 /// <reference path="my-base.js" />

    module MyModule {

        export class MyConcrete extends MyBase {

        }

    }

Upvotes: 3

Views: 1477

Answers (1)

basarat
basarat

Reputation: 275819

You need to declare the signature equivalent of your javascript code in typescript. This is to let TypeScript know what your JavaScript means if it was written in TypeScript:

declare module MyModule{
    export class MyBase{
        constructor(container, $MyElement);
        toString();
        method1():void;
        method2():bool;
    }
}

module MyModule {    
        export class MyConcrete extends MyBase {    
        }    
    }

Additionally /// <reference path="file" /> is for Typescript files only. For Javascript files you can use some script management (e.g. <script> tags, requireJS etc) to ensure MyBase is available before MyConcrete.

Upvotes: 4

Related Questions