Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {

        }

    }
like image 554
Amitabh Avatar asked Nov 18 '25 00:11

Amitabh


1 Answers

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.

like image 123
basarat Avatar answered Nov 19 '25 13:11

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!