How to write the Module Pattern in Typescript for an existing JavaScript Module Pattern

254 Views Asked by At

I am quite new to both Javascript and Typescript. I have to migrate the Javascript code into Typescript. Here is a Module pattern that returns itself instead of exposing private methods and property (Please correct me If I am wrong). So I don't know how to deal with this situation.

var MySocket = (function () {


    function MySocket(location, openCallback, closeCallback, errorCallback) {
        //Code Goes Here
    }



    MySocket.prototype.Open = function () {
        //Code Goes Here
    }

    MySocket.prototype.Close = function () {
        //Code Goes Here
    }



    return MySocket;
})();
1

There are 1 best solutions below

2
Dan On

This is called the revealing module pattern. You can still use this in TypeScript. The 'modern' pattern would be to remove the IIFE and return statement and instead add an export modifier to MySocket:

export function MySocket(location, openCallback, closeCallback, errorCallback) {
   //Code Goes Here
}

MySocket.prototype.Open = function () {
  //Code Goes Here
}

MySocket.prototype.Close = function () {
  //Code Goes Here
}

However, the usage of this is slightly different. ES6 modules are expected to be imported from other ES6 modules using the import statement rather than just referring to the variable by name:

import { MySocket } from './MySocket'