Refactor JavaScript code with closures into a TypeScript class

Looking to convert the following JavaScript code into a TypeScript class. The greet2 function within the prototype is being used as an immediately invoked function.

class Greeter {
    greeting: string;

    constructor(greeting: string) {
        this.greeting = greeting;
    }

    greet() {
        return "Hello, " + this.greeting;
    }

    //immediately invoked function
    greet2 = (() => {
        let blabla = 'Hello, ';
        return (foo: string) => {
            return blabla + foo;
        }
    })();

}

let greeter = new Greeter("world");  

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = () => {
    alert(greeter.greet2('tom'));
};

document.body.appendChild(button);

Answer №1

To define a property and initialize it on the prototype, you can follow this example:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
    greet2!: (foo) => string;  // in case of strictPropertyInitialization
    static staticInitializer() {
        // Through this method, we gain access to private members of `Greeter`.
        Greeter.prototype.greet2 = function(){
            let blabla = 'hello, ';
            return function greet2(this: Greeter, foo) {
                return blabla + foo;
            }
        }();
    }
}
Greeter.staticInitializer();

Upon implementation of this proposed update, a genuine static initializer will be available for use.

Answer №2

How can the JavaScript code below be rewritten as a TypeScript class?

One way is to use a property initializer:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
    
    greet2 = (() => {
        let blabla = 'hello, ';
        return function greet2(foo) {
            return blabla + foo;
        }
    })();
}

let greeter = new Greeter("world");

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
}

document.body.appendChild(button);

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

An issue was encountered while running a production version of an Ionic 2 Android app, as the ngfactory module could not be located

We encountered an error while running an Ionic2 app using the --prod flag. https://i.sstatic.net/LMLtS.png After the splashscreen loads, the screen turns white. The command we executed is: ionic run android --prod We are deploying on a Nexus 5x devi ...

Executing Mocha tests incorporating asynchronous setup code

I am currently creating test cases for a REST client library that requires "login" using the OAuth exchange to access the service. To avoid logging in for each individual endpoint I plan to test, I want to establish a "test setup," but I am unsure of the b ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...

Ignore TypeScript errors when using TSNode with Mocha by forcing the compiler to emit code despite errors and having TSNode execute the emitted code

Below is a code snippet where the function test2 is invalid, but it should not affect testing of function test1: export function test1(): boolean { return true; } export function test2(): number { return "1"; } Test: import { assert as Assert } fr ...

TypeScript made specifically for organizing and handling data within Supabase

I created a file named "types.ts" to efficiently utilize types generated with Supabase CLI. import { Database } from './database.types'; export type Tables<T extends keyof Database['public']['Tables']> = Database[&apo ...

Instead of displaying the downloadurl, the `[object Object]` is shown

The console is not displaying the downloadurl, instead [object,Object] [screenshot image]1 this.dbs.collection("databases").get().toPromise().then((snapshot) => { snapshot.docs.forEach(doc=>{ let name=doc.data().path; this.down=this. ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

Exploring the detection of changes in variables using Aurelia

Is it possible to track changes to a variable using aurelia? While I know that I can detect changes in a variable's type using @observable, I am curious if it is possible to monitor changes in a variable's value, for example from a = 3 to a = 4, ...

What is the way to create a `Partial<T>` specifically for nullable fields?

I have a requirement for a custom Partial<T> type that can transform nullable fields into optional ones. Currently, I am focusing on typing our ORM, which converts undefined values to null for nullable fields. In particular, I want to modify a type ...

No overload error encountered with TypeScript function call

I am working on an async function that communicates with the backend and I need it to handle axios error messages. My goal is to display these messages in a form. export async function register( prevState: string | undefined, formData: FormData ) { t ...

What is the method for filtering out specific fields in a template string?

I am currently working on defining constraints for the method field type event = { [k: `on${string}`]:(e:string)=>void } However, I need the event argument to be a number for fields that do not begin with 'on' type event = { [k: ` ...

Issues with Angular 9 application compatibility with IE11

Our Angular 9 project runs smoothly on Google Chrome and Firefox, but nothing appears on IE11. Despite trying various solutions found online and following related blogs, the issue remains unresolved. Here is a snippet from my tsconfig.json: { // Com ...

`Unceasing Replies Generated by the Function in Angular 2`

I am currently working with Angular 2 and facing an issue in displaying the user-nickname based on the User ID. Whenever I invoke the getUserName(userId) function from comments.component.html, it triggers the auth0 service to retrieve the user profile. Ho ...

Using an external npm module in TypeScript can result in the tsc output directory being modified

In my TypeScript project, I have set up the build process to generate JavaScript files in the ./src/ directory. Everything works smoothly when building against existing npm modules, such as Angular 2 imports. However, I encountered a strange issue when I ...

Substitute all instances of null bytes

I need to remove null bytes from a string. However, after replacing the null bytes \u0000 in the string let data = {"tet":HelloWorld.\u0000\u0000\u0000\u0000"} let test = JSON.parse(data).tet.replace("\u0000", ""); I always ...

What is the best way to ensure that TypeScript can work seamlessly with values that are subject to change

I am looking to create a scalable model for setting modals by using different body names. Currently, I have two types set: 'preference' and 'split'. The SetModal function takes a parameter of type body which should be one of these two v ...

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...