Best Practices for Converting TypeScript to JavaScript

What is the recommended approach to converting this JavaScript code into TypeScript?

JAVASCRIPT:

function MyClass() {
    var self = this,
        var1 = "abc",
        var2 = "xyz";

    // Public
    self.method1 = function () {
       return "something " + self.var1;
    };

    self.method2 = function (parm1) {
        var x = self.method1();
        return x + " something";
    };

    // Private 
    function func1(parm1, parm2) {
        return parm1 + parm2;
    }
}

This is how I envision writing it in TypeScript:

module MyNamespace {
    export class MyClass {

        private var1: string = "abc";
        private var2: string = "xyz";

        constructor() {
        }

        // Public
        public method1() {
            return "something " + self.var1;
        }
        public method2(parm1) {
            var x = this.method1();
            return x + " something";
        }

        // Private 
        private func1(parm1, parm2) {
            return parm1 + parm2;
        }
    }
}

The generated JavaScript places everything on the prototype leading to some scoping issues with "this":

var MyNamespace;
(function (MyNamespace) {
    var MyClass = (function () {
        function MyClass() {
            this.var1 = "abc";
            this.var2 = "xyz";
        }
        // Public
        MyClass.prototype.method1 = function () {
            return "something " + this.var1;
        };
        MyClass.prototype.method2 = function (parm1) {
            var x = this.method1();
            return x + " something";
        };

        // Private
        MyClass.prototype.func1 = function (parm1, parm2) {
            return parm1 + parm2;
        };
        return MyClass;
    })();
    MyNamespace.MyClass = MyClass;
})(MyNamespace || (MyNamespace = {}))

Although methods can be declared within the constructor and lambda functions can be used to address scoping issues, what are the best practices for porting JavaScript code to TypeScript?

Answer №1

However, the Javascript code generated places all properties on the prototype.

In my opinion, this is the desired behavior. The only time it becomes problematic is when passing the function as a callback. This is a well-known issue when dealing with callbacks and should be addressed at the appropriate time. I believe it is best to follow the JavaScript convention and embrace the system rather than resist it.

If each instance contains a unique function closure, it will consume more memory or create unnecessary work for the optimizer.

Answer №2

Your implementation for porting seems correct. It is advisable to keep class methods on the prototype for better memory management, performance, and reusability benefits. However, if there are certain methods that you prefer to have on the instance to maintain the context of 'this', you can utilize the member initialization + lambda syntax as shown below:

class MyClass {
    greeting = 'hello, ';

    /** someFunc is safe to use in callback positions */
    someFunc = (msg: string) => {
        console.log(this.greeting + msg);
    }
}

Answer №3

When working with JavaScript, it's important to remember that the value of this is determined at the time the method is called, not when it is declared. You can find more information about this concept on this Stack Overflow post (look under "The this variable").

To ensure you have the correct context, consider using the => arrow function.

class MyClass {
    greeting = 'hello, ';
    someFunc(msg: string) {
        console.log(this.greeting + msg);
    }
}

var m = new MyClass();
setTimeout(() => {m.someFunc("hello")},100);

When setting a timeout, a closure is created in the current scope. If there are large irrelevant variables present in the scope, it's best practice to declare a function outside of the scope that only includes relevant variables for the closure.

The following code snippet demonstrates how to create a closure function and limit the scope:

class MyClass {
    greeting = 'hello, ';
    someFunc(msg: string) {
        console.log(this.greeting + msg);
    }
    public static closures ={
        someFunc(me:MyClass,msg:string){
            return function(){
                me.someFunc(msg);
            };
        }
    }
}

var m = new MyClass();
setTimeout(MyClass.closures.someFunc(m,"hello"),100);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing computed properties: A guide to incorporating type setting

I currently have two separate interfaces defined for Person and Dog. interface Person { name: string; weight: number; } interface Dog { name: string; mass: number } const specificAttribute = isDog ? 'mass' : 'weight'; ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

Is there a way to live filter results using Vue?

Looking to apply a filter on my input v-model to search through a list of products. The current filter only shows items with an exact match to the input. How can I adjust it to display partial matches as the user types? Vue.filter('byName', fun ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

Updating an HTML value based on the selected option using JavaScript

I'm working on a form that included a select element: <select class="form-control"> <option>10 pc</option><!--1 USD --> <option>20 pc</option><!--2 USD --> <option>50 pc</option><!--3 USD ...

Error Encountered during Deployment of Custom React App on Heroku due to Fetch API Issue

After developing a small app using React without CRA, I successfully deployed it to Heroku. However, I encountered an issue where a static JSON file that I created isn't fetching properly (it works fine on my local machine). Upon encountering this pr ...

The Beauty of Organized Data: Understanding Multiple Columns in VUE JS Projects

I'm currently developing a VUE JS app that calculates route costs for employees based on specific route details. I am looking to create a VUE JS component that will only display a dropdown list with three columns: List of countries Day fee for each ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

Tips on how to highlight a clicked list item:

I'm currently attempting to access the key={1} Element within my li. My goal is to set the activeItem in State in order to compare it with the clicked item later on. If they are equivalent, I want to apply an active class to that specific element. How ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

The array is failing to pass through ajax requests

Here is the JavaScript code snippet for making an AJAX call. In this scenario, the code variable is used to store a C program code and then pass it on to the compiler.php page. function insert(){ var code = document.getElementById("file_cont").val ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

Submit a HTML form to a Telegram recipient

I am looking to send HTML form data, which includes input values and select options, to a telegram user. After some research, I discovered that I need to create a Telegram bot. I successfully created one using @botFather by following these steps: /newbot ...

Using the Async feature, I can retrieve the value of a string type when the return type of a function is Promise<any>

While working on a custom pipe, I encountered a situation that puzzled me. Can you explain why the code snippet below is considered valid? async transform(value: any): Promise<string> { let fullNameBasedOnPreference: string; fullNameBasedOnP ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Unforeseen behavior in event binding causing knockout knockout

I implemented an event binding for the scroll event on a DIV. To add debounce functionality to the handler, I created a function on my model that generates the debounced handler. Then, in my view, I bind this factory function. I assumed that my factory fu ...

What is the best way to dynamically load a personalized JavaScript file for individual users depending on their PHP login credentials?

Currently, I am conducting a web-based experiment in which students log into a website to take practice tests for a class. Initially, the students land on a login page that includes the following code: include_once("core/config.php"); include_once("core/ ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

JavaScript regular expression for detecting valid characters without repeating a specific character

let rx = /(\/MxML\/[a-z0-9\[\]@/]*)/gi; let s = 'If (/MxML/trades[1]/value== 1 then /MxML/trades[type=2]/value must be /MxML/stream/pre/reference@href'; let m; let res = []; while ((m = rx.exec(s))) { res.push(m[1]); ...