bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go.

The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself.

let MyClass = class{
  public property: any;
  public ok = 1;
}


let property = function(){ console.log(this.ok); }

// The goal is to make `this` refer to MyClass rather than its function

// First attempt
MyClass.prototype.property= property;

// Second attempt: using bind()
// But there's an issue because property is not always a function
let propertyBind = property.bind(MyClass)


// Third attempt: adding property while creating the class
let MyClass = class{
  public property = property ;
  public ok =1;
}

If property happens to be a function, we can't pass `this` as a parameter due to the constraint set by a third party for the class signature (without any parameters).

let property = (this)=>{ console.log(this.ok); }
``

Answer №1

class CustomClass {
  public data: any;
  public value = 1;
}

function addPropertyCustom<Base extends new (...args: any) => any, T>(
  baseClass: Base,
  property: T extends Function ? (this: InstanceType<Base>) => void : T
) {
  return class extends baseClass {
    public data = property;
  };
}

const CustomClass1 = addPropertyCustom(CustomClass, "hello");
const customClass1 = new CustomClass1();
console.log(customClass1.data); // "hello"

const CustomClass2 = addPropertyCustom(CustomClass, function () {
  // here `this` has type CustomClass
  this.value++;
});
const customClass2 = new CustomClass2();
customClass2.data();
console.log(customClass2.value); // 2

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

I'm attempting to grasp the concept of AngularJS's controllerAs notation

As I attempted to experiment with controllers by writing up a few examples, I encountered an issue where the controllers would not load. An error message appeared: firstController is not a function Upon doing some research, I discovered that Angular 1.3. ...

An error has occurred: TypeError - The class constructor $b802fbb11c9bd2dc$export$2e2bcd8739ae039 must be called with 'new'

I am attempting to integrate emoji-mart into my application, but I keep encountering a persistent error. Here is the snippet of code causing the issue: import data from '@emoji-mart/data' import { Picker } from 'emoji-mart' {showEmoji ...

Adjusting a NodeJS module for easier integration into codebases

I have organized some functions in a file within a node module structure... Here are the files and folder structure I created: - package.json - README.md - LICENSE.md - code |_______ code.js Currently, to use these functions, I include them like th ...

Optimize data storage with javascript on Otree

I've been attempting to store the timestamp from a click in an Otree database, but I've tried using various codes without success. Here's the first code snippet: function myFunction() { var n = Date.now(); document.getElementById(" ...

The jQuery .on("change") function keeps triggering repeatedly, but I'd like it to only execute once

I'm currently working on a feature that involves detecting changes to input text fields. Every time the user makes a change in an input field, I need to capture the new value and validate it. However, I've noticed that the code I have implemented ...

Filtering data at different levels in Javascript/Javascript programming language

Consider this array: var selection = ["14-3","19-5", "23-5", "40-8", "41-8"]; We now have two separate arrays: Array1 includes the first part of each value (before hyphens) in the original array, such as 1 ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

When using $.ajax, special characters are not rendered properly, displaying strange symbols instead of accents such as "é" or "ã"

I'm struggling to display the letter "é" using $.ajax and a JSON file. I've tried setting everything up with <meta charset="utf-8"> but all I get is an alert window showing "". Any help is appreciated, just not looking for PHP solutions. H ...

Determine the mean values to showcase at the center of a D3 donut graph

Check out this plunkr where I'm utilizing angularjs and d3.js. In the plunkr, I've created several donut charts. I'm interested in learning how to display the average data in the center of the arc instead of the percentage. Additionally, I& ...

The jQuery function for $(window).scroll is not functioning as expected

My challenge is getting the scroll to reveal my scrollTop value I've been working with this code: $(document).ready(function(){ console.log('Hello!'); $(window).scroll(function(){ console.log('Scrolling...'); var wScroll = ...

"In the most recent version of THREE.js (r82), the shadow is not detectable

I am having trouble casting a shadow from a cube onto a plane using MeshLambertMaterial in my code. Despite setting up the scene correctly, the shadows are not appearing as expected. Most solutions I have come across suggest that objects should be within ...

Strategies for capturing a module's thrown exception during loading process

Is there a way to validate environment variables and display an error message on the page if the environment is found to be invalid? The config.ts file will throw an exception if the env variable is invalid. import * as yup from 'yup' console. ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...

Are there any alternatives to Google Charts for creating charts?

There is a restriction of only 2k queries per month, which I find insufficient. Are there any alternative classes, plugins, or tools that can be used to generate charts similar to those created by Google Charts? Thank you. ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...