Creating a progressive prototype chain in TypeScript: A step-by-step guide

With JavaScript, it is possible to create a "derived class" whose "base class" is dynamic using code like the following:

function NewBaseClass(sF) { 
  function DynamicBaseClass(iF) { this.instanceField = iF; }
  // EDIT: oops, this is not really static in the ES6 sense, but it's in the
  //       "base" prototype and, importantly, is NOT in the final object.
  DynamicBaseClass.prototype.staticField = sF;
  return DynamicBaseClass;
}
function NewDerivedClass(baseClass) {
  function DerivedClass(iF, dF) {
    baseClass.call(this, iF);
    this.derivedField = dF;
  }
  DerivedClass.prototype = Object.create(baseClass.prototype);
  Object.defineProperty(DerivedClass.prototype, 'constructor', { 
    value: DerivedClass,
    enumerable: false, // omit from 'for in' loop
    writable: true
  });
  DerivedClass.prototype.dump = function dump() {
    console.log("instanceField=" + this.instanceField +
        " derivedField=" + this.derivedField + 
        " staticField=" + this.staticField + 
        " base=" + this.__proto__.__proto__.constructor.name);
  }
  return DerivedClass;
}
var BaseClass1 = NewBaseClass("dynamic prototype #1");
var BaseClass2 = NewBaseClass("dynamic prototype #2");
new (NewDerivedClass(BaseClass1))(3, 33).dump();
new (NewDerivedClass(BaseClass1))(4, 44).dump();
new (NewDerivedClass(BaseClass2))(5, 55).dump();
new (NewDerivedClass(BaseClass2))(6, 66).dump();
// Output:
//   instanceField=3 derivedField=33 staticField=dynamic prototype #1 base=DynamicBaseClass
//   instanceField=4 derivedField=44 staticField=dynamic prototype #1 base=DynamicBaseClass
//   instanceField=5 derivedField=55 staticField=dynamic prototype #2 base=DynamicBaseClass
//   instanceField=6 derivedField=66 staticField=dynamic prototype #2 base=DynamicBaseClass

(There are various reasons for utilizing this approach, such as saving memory by allowing multiple objects to share common values efficiently within the prototype chain.)

If you want to achieve a similar effect with TypeScript, it is acceptable for the class definition code to be somewhat messy as long as you can write new (NewDerivedClass(BaseClass)) in a way that provides a reasonable type.

Answer №1

Using ES2015 classes

By utilizing the extends keyword with a variable, it is possible to shift from functional class constructors to ES2015-style classes.

function NewBaseClass(sF: string) { 
    return class {
        staticField = sF;
        instanceField: number;

        constructor(iF: number) {
            this.instanceField = iF;
        }
    };
}

interface SuperclassType {
    new(iF: number): {
        instanceField: number;
        staticField: string;
    };
}

function NewDerivedClass(baseClass: SuperclassType) {
    return class extends baseClass {
        derivedField: number;
        constructor(iF: number, dF: number) {
            super(iF);
            this.derivedField = dF;
        }

        dump() {
            console.log("instanceField=" + this.instanceField +
                " derivedField=" + this.derivedField + 
                " staticField=" + this.staticField);
        }
    };
}

var BaseClass1 = NewBaseClass("dynamic prototype #1");
var BaseClass2 = NewBaseClass("dynamic prototype #2");
new (NewDerivedClass(BaseClass1))(3, 33).dump();
new (NewDerivedClass(BaseClass1))(4, 44).dump();
new (NewDerivedClass(BaseClass2))(5, 55).dump();
new (NewDerivedClass(BaseClass2))(6, 66).dump();

// Output:
//   instanceField=3 derivedField=33 staticField=dynamic prototype #1
//   instanceField=4 derivedField=44 staticField=dynamic prototype #1
//   instanceField=5 derivedField=55 staticField=dynamic prototype #2
//   instanceField=6 derivedField=66 staticField=dynamic prototype #2

issue #4890.

Implementing ES2015 static

It should be noted that the above implementation does not utilize TypeScript's static feature effectively, since the static field is placed on the anonymous prototype object of NewBaseClass instead of the constructor function itself. This issue can be resolved by referencing the base class object in the derivation function rather than treating it as a raw property.

function NewBaseClass(sF: string) { 
    return class {
        static staticField = sF;  // <-- static
        instanceField: number;

        constructor(iF: number) {
            this.instanceField = iF;
        }
    };
}

interface SuperclassType {
    staticField: string;  // <-- static
    new(iF: number): {
        instanceField: number;
    };
}

function NewDerivedClass(baseClass: SuperclassType) {
    return class extends baseClass {
        derivedField: number;
        constructor(iF: number, dF: number) {
            super(iF);
            this.derivedField = dF;
        }

        dump() {
            console.log("instanceField=" + this.instanceField +
                " derivedField=" + this.derivedField + 
                " staticField=" + baseClass.staticField);  // <-- superclass reference
        }
    };
}

playground

Utilizing functional class constructors

Although not very readable, it is feasible to achieve strong typing using this approach without altering the existing code structure. However, based on issues such as #2299 and #2310, expressing this securely while maintaining functional syntax seems challenging. As per your request, the cast is redirected via unknown.

function NewDerivedClass<T extends BaseClassConstructor>(baseClass: T):
    DerivedClassConstructor<T> {
  function DerivedClass(
      this: InstanceType<BaseClassConstructor> & { derivedField: number },
      iF: number,
      dF: number) {
    baseClass.call(this, iF);
    this.derivedField = dF;
  }
  DerivedClass.prototype = Object.create(baseClass.prototype);
  Object.defineProperty(DerivedClass.prototype, 'constructor', {
    value: DerivedClass,
    enumerable: false, // omit from 'for in' loop
    writable: true
  });
  DerivedClass.prototype.dump = function dump() {
    console.log("instanceField=" + this.instanceField +
      " derivedField=" + this.derivedField +
      " staticField=" + this.staticField +
      " base=" + this.__proto__.__proto__.constructor.name);
  }
  return DerivedClass as unknown as DerivedClassConstructor<T>;
}

As demonstrated in the playground link below, this setup allows for all described cases in the question to be executed seamlessly, along with providing strongly-typed access to SomeOtherClass.someOtherField.

With ES2015 classes

Because the extends keyword can take a variable, you can convert away from functional class constructors and into ES2015-style classes.

function NewBaseClass(sF: string) { 
    return class {
        staticField = sF;
        instanceField: number;

        constructor(iF: number) {
            this.instanceField = iF;
        }
    };
}

interface SuperclassType {
    new(iF: number): {
        instanceField: number;
        staticField: string;
    };
}

function NewDerivedClass(baseClass: SuperclassType) {
    return class extends baseClass {
        derivedField: number;
        constructor(iF: number, dF: number) {
            super(iF);
            this.derivedField = dF;
        }

        dump() {
            console.log("instanceField=" + this.instanceField +
                " derivedField=" + this.derivedField + 
                " staticField=" + this.staticField);
        }
    };
}

var BaseClass1 = NewBaseClass("dynamic prototype #1");
var BaseClass2 = NewBaseClass("dynamic prototype #2");
new (NewDerivedClass(BaseClass1))(3, 33).dump();
new (NewDerivedClass(BaseClass1))(4, 44).dump();
new (NewDerivedClass(BaseClass2))(5, 55).dump();
new (NewDerivedClass(BaseClass2))(6, 66).dump();
// Output:
//   instanceField=3 derivedField=33 staticField=dynamic prototype #1
//   instanceField=4 derivedField=44 staticField=dynamic prototype #1
//   instanceField=5 derivedField=55 staticField=dynamic prototype #2
//   instanceField=6 derivedField=66 staticField=dynamic prototype #2

playground

One hazard of this approach is that you can't accept and amend a generic as part of NewDerivedClass, which prevents you from amending an arbitrary class—due, in part, to the possibility that you'll introduce a name collision. See issue #4890.

With ES2015 static

Note that the above doesn't use Typescript's static, as you've effectively put the static field on the NewBaseClass's anonymous prototype object rather than on the constructor function itself. This is easily remedied by referring to the base class object in your derivation function, rather than treating it as a raw property.

function NewBaseClass(sF: string) { 
    return class {
        static staticField = sF;  // <-- static
        instanceField: number;

        constructor(iF: number) {
            this.instanceField = iF;
        }
    };
}

interface SuperclassType {
    staticField: string;  // <-- static
    new(iF: number): {
        instanceField: number;
    };
}

function NewDerivedClass(baseClass: SuperclassType) {
    return class extends baseClass {
        derivedField: number;
        constructor(iF: number, dF: number) {
            super(iF);
            this.derivedField = dF;
        }

        dump() {
            console.log("instanceField=" + this.instanceField +
                " derivedField=" + this.derivedField + 
                " staticField=" + baseClass.staticField);  // <-- superclass reference
        }
    };
}

playground

With functional class constructors

This is unlikely to result in very readable code, but it can be done with strong typing (outside of your derived classes) without changing your code. Per related issues #2299 and #2310, it doesn't seem like there will be a good way to express this safely while using functional syntax. I've kept it using your syntax, and (as recommended in the threads) I redirect the cast via unknown.

function NewDerivedClass<T extends BaseClassConstructor>(baseClass: T):
    DerivedClassConstructor<T> {
  function DerivedClass(
      this: InstanceType<BaseClassConstructor> & { derivedField: number },
      iF: number,
      dF: number) {
    baseClass.call(this, iF);
    this.derivedField = dF;
  }
  DerivedClass.prototype = Object.create(baseClass.prototype);
  Object.defineProperty(DerivedClass.prototype, 'constructor', {
    value: DerivedClass,
    enumerable: false, // omit from 'for in' loop
    writable: true
  });
  DerivedClass.prototype.dump = function dump() {
    console.log("instanceField=" + this.instanceField +
      " derivedField=" + this.derivedField +
      " staticField=" + this.staticField +
      " base=" + this.__proto__.__proto__.constructor.name);
  }
  return DerivedClass as unknown as DerivedClassConstructor<T>;
}

As you can see in the playground link below, this allows all of the cases you've described in your question, verbatim, and also allows strongly-typed access to SomeOtherClass.someOtherField.

playground

Unique solution

In TypeScript, achieving the desired effect can be done with the following code (staticField is accessible on the prototype chain rather than on the derived object). It's worth noting that using a truly static field in the base class simplifies the process by eliminating the need for as BaseClass in NewBaseClass.

  • TypeScript 3.8.3 may not fully accept this approach and might generate an error regarding DerivedClass, stating "A mixin class must have a constructor with a single rest parameter of type 'any[]'". However, this error can be suppressed with // @ts-ignore.
  • On TypeScript 3.6.5, it seems that baseClass is not recognized as non-empty, leading to multiple errors. Additionally, a peculiar message "Return type of exported function has or is using private name 'DerivedClass'" is displayed despite NewDerivedClass not being exported. One workaround for the latter issue involves defining a corresponding interface and specifying it as the return type:

    interface DerivedClass_ {
      new (iF: number, dF: number): {
        derivedField: number;
        dump(): void;
      }
    }
    
interface BaseClass {
  new (iF: number): {
    instanceField: number;
    staticField: string;
  };
}
function NewBaseClass(sF: string): BaseClass {
  // Implementation details here
}
function NewDerivedClass<Base extends BaseClass>(baseClass: Base) {
  // More implementation details here
}
// Additional code snippets and usage example

The output from the compiler mirrors the implemented logic and functions correctly within TS 3.6.3.

One part of the generated script utilizes Object.setPrototypeOf, which according to MDN should be used judiciously due to performance considerations. Hopefully, the TypeScript team has optimized its usage!

Innovative strategy for data sharing

If the intention is solely to share data across instances without burdening individual memory allocations, a simpler method like the one demonstrated below can achieve the same outcome:

interface DynamicClass_ { // Only applicable pre-TypeScript 3.8
  new (iF: number, dF: number): {
    instanceField: number;
    derivedField: number;
  };
}
function NewClass(staticField: string, foo: any): DynamicClass_ {
  // Efficient data sharing technique implementation
}

An intriguing aspect is how dump() function references parameters directly without storing them elsewhere in the class! The JavaScript runtime typically creates heap objects for class functions such as dump() to utilize. Logically, these parameters (staticField, etc.) cannot reside directly in the instance (this) since altering

this</code through operations like <code>new (NewClass(...))(...).dump.bind(otherThis)
would still maintain access to NewClass's parameters in the rebounded dump.

It's probable that objects representing functions within DynamicClass are freshly generated each time NewClass is called, considering their accessibility in JS programs. Hence, any approach involving returning classes or functions from another function will incur some memory overhead. Depending on the context, this cost may vary compared to storing data in class instances.

For debugging purposes, copying parameters into the prototype may prove beneficial when utilizing this methodology:

function NewClass(staticField: string): DynamicClass_ {
  // Prototype alteration for debugging assistance
}

General solution

The following code produces the same effect in TypeScript (staticField is on the prototype chain and not on the derived object). Note, however, that using a truly static field in the base class is easier: you won't need to write as BaseClass in NewBaseClass.

  • TypeScript 3.8.3 doesn't fully accept it: it complains about DerivedClass, saying "A mixin class must have a constructor with a single rest parameter of type 'any[]'". However this error can be be suppressed with // @ts-ignore.
  • TypeScript 3.6.5 doesn't seem to understand that baseClass is non-empty and therefore gives multiple errors. It also says "Return type of exported function has or is using private name 'DerivedClass'" which is weird since NewDerivedClass is not exported. A workaround for the latter error is to define a matching interface and use it as the return type:

    interface DerivedClass_ {
      new (iF: number, dF: number): {
        derivedField: number;
        dump(): void;
      }
    }
    
interface BaseClass {
  new (iF: number): {
    instanceField: number;
    staticField: string;
  };
}
function NewBaseClass(sF: string): BaseClass {
  class DynamicBaseClass {
    instanceField: number;
    staticField?: string; // a value assigned here wouldn't be on the prototype
    constructor(iF: number) { this.instanceField = iF; }
  }
  DynamicBaseClass.prototype.staticField = sF;
  return DynamicBaseClass as BaseClass;
}
function NewDerivedClass<Base extends BaseClass>(baseClass: Base) {
  // @ts-ignore "A mixin class must have a constructor with a single rest parameter..."
  class DerivedClass extends baseClass {
    derivedField: number;
    constructor(iF: number, dF: number) {
      super(iF);
      this.derivedField = dF;
    }
    dump() {
      console.log("instanceField=" + this.instanceField +
          " derivedField=" + this.derivedField + 
          " staticField=" + this.staticField +
          " base=" + (this as any).__proto__.__proto__.constructor.name);
    }
  }
  return DerivedClass;
}
var BaseClass1 = NewBaseClass("dynamic prototype chain #1");
var BaseClass2 = NewBaseClass("dynamic prototype chain #2");
new (NewDerivedClass(BaseClass1))(3, 33).dump();
new (NewDerivedClass(BaseClass1))(4, 44).dump();
new (NewDerivedClass(BaseClass2))(5, 55).dump();
new (NewDerivedClass(BaseClass2))(6, 66).dump();

The compiler's output looks like this in TS 3.6.3 and works as expected:

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
function NewBaseClass(sF) {
    var DynamicBaseClass = /** @class */ (function () {
        function DynamicBaseClass(iF) {
            this.instanceField = iF;
        }
        return DynamicBaseClass;
    }());
    DynamicBaseClass.prototype.staticField = sF;
    return DynamicBaseClass;
}
function NewDerivedClass(baseClass) {
    // @ts-ignore "A mixin class must have a constructor with a single rest parameter of type 'any[]'."
    var DerivedClass = /** @class */ (function (_super) {
        __extends(DerivedClass, _super);
        function DerivedClass(iF, dF) {
            var _this = _super.call(this, iF) || this;
            _this.derivedField = dF;
            return _this;
        }
        DerivedClass.prototype.dump = function () {
            console.log("instanceField=" + this.instanceField +
                " derivedField=" + this.derivedField +
                " staticField=" + this.staticField +
                " base=" + this.__proto__.__proto__.constructor.name);
        };
        return DerivedClass;
    }(baseClass));
    return DerivedClass;
}
var BaseClass1 = NewBaseClass("dynamic prototype chain #1");
var BaseClass2 = NewBaseClass("dynamic prototype chain #2");
new (NewDerivedClass(BaseClass1))(3, 33).dump();
new (NewDerivedClass(BaseClass1))(4, 44).dump();
new (NewDerivedClass(BaseClass2))(5, 55).dump();
new (NewDerivedClass(BaseClass2))(6, 66).dump();

I see it uses Object.setPrototypeOf which MDN warns us not to use for performance reasons. I hope the TypeScript people know what they are doing!

Technique for "cheap" data sharing

If the goal is simply to share data among many instances without consuming any memory on individual instances, it can be done much more simply like this:

interface DynamicClass_ { // not needed in TypeScript 3.8
  new (iF: number, dF: number): {
    instanceField: number;
    derivedField: number;
  };
}
function NewClass(staticField: string, foo: any): DynamicClass_ {
  class DynamicClass {
    constructor(public instanceField: number, 
                public derivedField: number) { }
    dump() {
      console.log("instanceField=" + this.instanceField +
          " derivedField=" + this.derivedField + 
          " staticField=" + staticField + // <<<<<<<<<<<<<<<<<<<<<<<<<
          " foo=" + foo);                 // <<<<<<<<<<<<<<<<<<<<<<<<<
    }
  }
  return DynamicClass;
}

Notice that dump() can reference parameters without storing them in the class anywhere! In general, the JS runtime must create some kind of heap object for class functions like dump() to share. Logically, it cannot store the parameters (staticField etc.) in the instance (this), because it is possible to change this using code like

new (NewClass(...))(...).dump.bind(otherThis)
- and yet the rebound dump will still have access to parameters of NewClass.

I'm pretty sure that the objects representing the functions inside DynamicClass must be created anew every time NewClass is called, because these objects are accessible to JS programs. So any technique that involves returning classes or functions from another function will incur a certain memory cost. Depending on the circumstances, this cost may be smaller or larger than storing data in the class instances.

When using this technique, it can be useful to copy parameters into the prototype for debugging purposes:

function NewClass(staticField: string): DynamicClass_ {
  class DynamicClass {
    ...
  }

  let proto: any = DynamicClass.prototype;
  proto.staticField = staticField;

  return DynamicClass;
}

Answer №2

Unique solution

In TypeScript, achieving the desired effect can be done with the following code (staticField is accessible on the prototype chain rather than on the derived object). It's worth noting that using a truly static field in the base class simplifies the process by eliminating the need for as BaseClass in NewBaseClass.

  • TypeScript 3.8.3 may not fully accept this approach and might generate an error regarding DerivedClass, stating "A mixin class must have a constructor with a single rest parameter of type 'any[]'". However, this error can be suppressed with // @ts-ignore.
  • On TypeScript 3.6.5, it seems that baseClass is not recognized as non-empty, leading to multiple errors. Additionally, a peculiar message "Return type of exported function has or is using private name 'DerivedClass'" is displayed despite NewDerivedClass not being exported. One workaround for the latter issue involves defining a corresponding interface and specifying it as the return type:

    interface DerivedClass_ {
      new (iF: number, dF: number): {
        derivedField: number;
        dump(): void;
      }
    }
    
interface BaseClass {
  new (iF: number): {
    instanceField: number;
    staticField: string;
  };
}
function NewBaseClass(sF: string): BaseClass {
  // Implementation details here
}
function NewDerivedClass<Base extends BaseClass>(baseClass: Base) {
  // More implementation details here
}
// Additional code snippets and usage example

The output from the compiler mirrors the implemented logic and functions correctly within TS 3.6.3.

One part of the generated script utilizes Object.setPrototypeOf, which according to MDN should be used judiciously due to performance considerations. Hopefully, the TypeScript team has optimized its usage!

Innovative strategy for data sharing

If the intention is solely to share data across instances without burdening individual memory allocations, a simpler method like the one demonstrated below can achieve the same outcome:

interface DynamicClass_ { // Only applicable pre-TypeScript 3.8
  new (iF: number, dF: number): {
    instanceField: number;
    derivedField: number;
  };
}
function NewClass(staticField: string, foo: any): DynamicClass_ {
  // Efficient data sharing technique implementation
}

An intriguing aspect is how dump() function references parameters directly without storing them elsewhere in the class! The JavaScript runtime typically creates heap objects for class functions such as dump() to utilize. Logically, these parameters (staticField, etc.) cannot reside directly in the instance (this) since altering

this</code through operations like <code>new (NewClass(...))(...).dump.bind(otherThis)
would still maintain access to NewClass's parameters in the rebounded dump.

It's probable that objects representing functions within DynamicClass are freshly generated each time NewClass is called, considering their accessibility in JS programs. Hence, any approach involving returning classes or functions from another function will incur some memory overhead. Depending on the context, this cost may vary compared to storing data in class instances.

For debugging purposes, copying parameters into the prototype may prove beneficial when utilizing this methodology:

function NewClass(staticField: string): DynamicClass_ {
  // Prototype alteration for debugging assistance
}

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

Utilize React to iterate through data retrieved from firebase

I'm currently facing an issue with Google Firebase Realtime database where I am unable to create an array of the collection. Whenever I loop through the const return in console log, I receive messages as individual objects. However, what I actually n ...

Utilizing statuses in Typescript React for conditional rendering instead of manually checking each individual variable

It's common for developers, myself included, to perform conditional rendering by checking variable values like this: import React, { useState, useMemo } from 'react' const Page = () => { const [data, setData] = useState<any[]>() ...

fetching data with Contentful and GatsbyJS

I am currently working on fetching data from Contentful using GraphQL within a Gatsby application, and here is my approach: type AllContentfulBlogs = { allContentfulBlogs: { nodes: Array<{ title?: string | null | undefined, ...

The partial template is not functioning as anticipated

Introducing an interface designed to accept two templates, with the resulting function being a partial of one of them (similar to React-Redux): export type IState<TState, TOwnProps> = { connect: (mapStateToProps: MapStateToProps<TState, Parti ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

The error message "Property 'xy' is not found within the type '{}'. TS2339" indicates that the 'xy' property is not present

I've embarked on setting up a compact project utilizing react / typescript featuring the components below: App.tsx import React from "react"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; import Styles ...

The Jest test is experiencing a failure as a result of an imported service from a .ts file

In my Jest test file with a .spec.js extension, I am importing an index.js file that I need to test. Here is the code snippet from the .spec.js file: var HttpService = require('./index.js').HttpService; The problem arises because the index.js f ...

Guide to simulating a function using .then within a hook

I am using a function that is called from a hook within my component. Here is my component: ... const handleCompleteContent = (contentId: string) => { postCompleteContent(contentId, playerId).then(data => { if (data === 201) { ... The caller ...

How can I limit a type parameter to only be a specific subset of another type in TypeScript?

In my app, I define a type that includes all the services available, as shown below: type Services = { service0: () => string; service1: () => string; } Now, I want to create a function that can accept a type which is a subset of the Service ...

TS Intellisense in Visual Studio Code for JavaScript Events and File Types

Whilst attempting a similar action, onDragOver(event: Event): void in Visual Studio Code, an error is thrown by IntelliSense: [ts] Cannot find name 'Event'. The same issue arises when trying something like this: let file: File = new File() ...

Accessing the .env file to configure a NestJS application using TypeORM and a custom provider

I am still learning my way around nestJS and I am currently trying to configure .env for an existing application but encountering some issues. Within my custom provider for the appModule, it looks like this: @Module({ providers: [ AbcService, ...

To determine if two constant objects share identical structures in TypeScript, you can compare their properties

There are two theme objects available: const lightMode = { background: "white", text: { primary: "dark", secondary: "darkgrey" }, } as const const darkMode = { background: "black", text: { prim ...

"The list of table rows in a React application using Typescript is not rendering properly

I am encountering an issue where the rows in my table are not being rendered while trying to map objects from a list called items. I am working with typescript and react-bootstrap. Can someone help me understand why this is happening and how to resolve it? ...

Implement a default dropdown menu that displays the current month using Angular and TypeScript

I am looking to implement a dropdown that initially displays the current month. Here is the code snippet I have used: <p-dropdown [options]="months" [filter]="false" filterBy="nombre" [showClear] ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

Transitioning an NX environment to integrate ESM

My NX-based monorepo is quite extensive, consisting of half a dozen apps, frontend, backend, and dozens of libs. Currently, everything is set up to use commonjs module types, as that's what the NX generators have always produced. However, many librar ...

I seem to be encountering an issue with my Angular 6 HTTP PUT request

Below is the code snippet: products.service: updateCategorie(ucategorie: Icategorie) { const endpoint = this.url + 'api/Category/Edit'; const headers = new Headers(); headers.append('Authorization', 'Bearer ' + localStorage ...

Make sure to incorporate the .gitignored files that are compiled from typescript when running the `npm install -g

Looking for a way to ignore the JavaScript files compiled from TypeScript in my git repository to make merging, rebasing, and partial commits easier. Here's how I have it set up: tsconfig.json { "compilerOptions": { "outDir": "./dist" ...