Having trouble accessing a property from a child class instance in Typescript after calling the super constructor

Exploring how to implement inheritance in Typescript has been an interesting journey. I started by creating a base class Model structured like this:

export class Model {

  [key: string]: any;

  public errors?: {
    [key in keyof Model]: string;
  };

  constructor(model?: { [key in keyof Model]: Model[key] }) {
    if (model) {
      Object.assign<Model, Model>(this, model);
    }
  }
}

After that, I moved on to writing a test file featuring the following code:

import {Model} from './Model';

describe('Model', () => {
  class ChildModel extends Model {
    public name: string;
  }

  it('create model from object', () => {
    const name: string = 'Test Model';
    const childModel: ChildModel = new ChildModel({
      name,
    });
    expect(childModel.name).toEqual(name);
  });
});

During my debugging efforts within the base class constructor scope, I noticed that while the input model properties were successfully mapped into the class instance, the child class instance seemed unable to access these mapped properties. Despite researching extensively online and even attempting various strategies like placing the super call as the first line in the child class constructor or creating a default constructor with a super call, the tests continued to fail.

Interestingly, when running the code on CodeSandbox, everything worked perfectly. To witness the error occurring firsthand, please clone this repository and execute yarn test.

Answer №1

To solve the issue, try experimenting with your code and see if removing the name property in your extended class helps.

describe('Model', () => {
  class ChildModel extends Model { }

  it('create model from object', () => {
    const name: string = 'Test Model';
    const childModel: ChildModel = new ChildModel({
      name,
    });
    expect(childModel.name).toEqual(name);
  });
});

The discrepancy in the order of object constructor initialization is likely due to different compilation targets between codesandbox (ES6) and react-scripts (ES5).

For more information, check out this stackoverflow thread and also this GitHub issue.

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

The function type is not as strict as the return type in terms of enforcement

I am working on defining a function type that enforces the return type (Object) to have the exact object properties specified in the return type definition. Despite my efforts, the compiler is not enforcing strict adherence to the returned object properti ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Converting an object into an array using React and TypeScript

Extracted from a form is an object with input, output, and outputType fields that can vary between number, string, and boolean types. To display the information in a table without the output type, I have created a mapped obj. However, I also need to prese ...

The closeOnClickOutside feature seems to be malfunctioning in the angular-2-dropdown-multiselect plugin

I'm currently using 2 angular-2-dropdown-multiselect dropdowns within a bootstarp mega div. The issue I'm facing is that when I click on the dropdown, it opens fine. However, when I click outside of the dropdown, it doesn't close as expected ...

multer image upload in NodeJS and Angular is throwing an error stating that req.file is undefined

I've been facing an issue while trying to upload an image for a blog post using Multer. My backend consists of mongodb and NodeJS, while Angular is used for the frontend. Despite performing the POST request, I always find that req.file remains undefin ...

Initial values of dual knob settings on Ionic Range and their ability to update dynamically

As someone new to using Ionic and TypeScript, I am facing challenges in setting initial values for my Ionic Range component (V5). Referring to other posts, it seems that there are upper and lower properties within ngModel, but I'm unsure about the bes ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

The term 'Employee' is typically used as a classification, but in this context, it is being treated as a specific value

I am encountering an issue while trying to define a variable as type Employee. The error message 'Employee' only refers to a type but is being used as a value here. ts(2693) keeps appearing. Here is my show-api.ts code: import { Component, OnIni ...

The server on Localhost:3000 encountered an issue with a middleware error while attempting to utilize the upload feature with Dropbox

I've encountered an issue that I'm struggling to fix. The only solution I found for resolving errors in this file was the following: import { clerkMiddleware } from '@clerk/nextjs/server'; import { NextResponse } from 'next/server& ...

When working with Typescript, the error "Unable to locate type 'require'" may be encountered

I am attempting to incorporate the type definition file available at https://www.npmjs.com/package/diff-match-patch into my Angularjs project. Just a heads up: I am working with Visual Studio as my IDE var DiffMatchPatch = require('diff-match-patch& ...

"Exploring the wonders of Node.js integration with Azure KeyVault

After receiving a certificate from an Azure Key Vault with the code snippet: const certificate = await keyVaultClient.getCertificate(this.keyVaultUri, certificateName, ''); I successfully obtained the certificate, which was a good start :) How ...

Exploring the different categories within object destructuring

Here's an interesting scenario: const { foo: IFoo[] } = bar; This situation, along with the following: const { foo: Array<IFoo> } = bar; could potentially lead to errors. However, if you have something like this: const { foo: TFoo } = bar; ...

Demonstrating a feature in a custom Angular Material dialog box

I have a reusable custom Material UI Dialog that I want to utilize to show different components. For instance, I would like to display a Login component on one occasion and a Registration component on another. However, the issue arises when I assign my com ...

The unit test is not passing due to inconsistencies between the mock data generated in the constructors and the original mock data

Currently, I am delving into the world of unit testing and have created a test to work on. Here is what I have so far: const EXEPECTED: MergedFood = { id: '1', name: 'test mergedFood', ingredients: { '2': ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Creating a type-safe method wrapper in TypeScript based on function names

Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code: function wrap(API, fnName, fn) { const origFn = API.p ...

`Managing an array of categories in each element with rxjs filter: A guide`

I'm in the process of adding a sorting feature to my ionic/angular app. The app pulls vouchers from an API, each belonging to different categories. I need the system to be flexible enough to support multiple categories per voucher. Currently, the solu ...

The parameter 'Barable' cannot be assigned to the parameter 'T' as they are not compatible

Could anyone help me understand why this code isn't functioning as intended: class Fooable { foo: string; } class Barable extends Fooable { bar: boolean; } function simplifiedExample<T extends Fooable>(): Array<T> { let list ...

The property 'navCtrl' cannot be read as it is undefined

I have been struggling for hours to find a solution to the issue in my project. Despite reading several other posts on the "Cannot read property ... of undefined" error, I am unable to resolve it. Below is the relevant code snippet from my Ionic 2 / Apach ...

Bang colon notation in Angular is a powerful feature that allows developers to interact with

While browsing through the Angular Deprecation docs, I stumbled upon the use of `!:` notation. @Input() tpl !: TemplateRef<any>; @ContentChild(TemplateRef) inlineTemplate !: TemplateRef<any>; This same notation was also found here as well. @ ...