A circular reference occurs when a base class creates a new instance of a child class within its own definition

My goal is to instantiate a child class within a static method of the base class using the following code:

class Baseclass {
    public static create(){
        const newInstance = new Childclass();
        return newInstance;
    }
}

class Childclass extends Baseclass {}

const anInstance = Baseclass.create();

This implementation behaves as expected. However, when attempting to split each class into separate files, I encounter the error:

TypeError: Class extends value undefined is not a constructor or null

An example can be viewed here. I suspect this issue is related to imports causing circular references. Despite successful execution when both classes are in the same file, I anticipate it should also function properly when separated into distinct files.

Answer №1

After some research on a GitHub issue and a related GitHub repository addressing the problem, I discovered that the solution involves using `index.ts` file like so:

export { Baseclass } from './baseclass';
// NOTE: Placing this line first causes an issue.
export { Childclass } from './childclass';

Then, you can simply reference the `index.ts` file instead of individual ones. You can check out this example for more details.

Answer №2

Placing the classes Baseclass and Childclass in separate modules results in a circular reference issue between them that cannot be resolved using ES modules; Baseclass requires Childclass to be imported for its definition, and vice versa.

The root of the problem lies with Baseclass. It should not directly reference its child class because it is meant to be independent of its descendants. If there needs to be a factory method, it can use this as the constructor in a static method. Alternatively, if base classes are not intended to be instantiated on their own, they can be marked as abstract:

abstract class Baseclass {
    public static create(){
        return new this();
    }
}

class Childclass extends Baseclass {}

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

What causes TypeScript to convert a string literal union type to a string when it is assigned in an object literal?

I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved. Let me illustrate with a simple example: let foo = false; const bar = foo ? 'foo' : 'bar' ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Module 'csstype' not found

I am diving into the world of React with TypeScript. After setting up react and react-dom, I also installed @types/react and @types/react-dom which all went smoothly. However, a pesky error message keeps popping up: ERROR in [at-loader] ./node_modules/@t ...

React Typescript Context state isn't refreshing properly

Struggling to modify my context state, I feel like I'm overlooking something as I've worked with context in the past. The challenge lies in changing the 'isOpen' property within the context. You can view my code here: CodeSand **app.ts ...

Nestjs: Accessing the request or context using a Decorator

In my current project using NestJS, I am attempting to make the executionContext accessible in a logger for the purpose of filtering logs by request. Each injectable has its own instance of a logger, and I want to maintain this setup (where the scope of t ...

Pipe for Angular that allows for searching full sentences regardless of the order of the words

I am looking to create a search bar that can search for the 'title' from the table below, regardless of the word order in the sentence. I attempted to use a filter pipe to check if the search string exists in the title. I also experimented with ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Creating an array in TypeScript is a versatile and powerful feature that

While I have some familiarity with TypeScript, there is one thing that continues to intrigue me. I understand the distinction between Array<string> and string[]. I am aware that these declarations can be used interchangeably, such as: export class S ...

How do I incorporate global typings when adding type definitions to an npm module?

Suppose I create a node module called m. Later on, I decide to enhance it with Typescript typings. Luckily, the module only exports a single function, so the m.d.ts file is as follows: /// <reference path="./typings/globals/node/index.d.ts" /> decl ...

Decoding the HTML5 <video> tag using the html-react-parser library

I'm working on a NextJS V13 app where I need to display HTML content fetched from a CMS. Instead of using dangerouslySetHtml, I opted for the html-react-parser package to parse the HTML and replace certain embedded tags like <a>, <img>, an ...

Jasmine: utilizing unit test to spy on the invocation of a nested function

When running unit tests for an Angular app, I need to spy on a function called func1 to check if it is being called. However, within func1 there is a call to func2 and I also want to spy on that to see if it is being called. How should I structure my unit ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

The KeyValuePair<string, Date> type in Typescript cannot be assigned to the KeyValuePair<number, string> type

I encountered the following issue: An error occurred stating that Type 'KeyValuePair<string, Date>' is not assignable to type 'KeyValuePair<number, string>'. Also, it mentioned that Type 'string' is not assignab ...

Using a static enum in a different class in TypeScript: A guide

After referencing this question and answer on Stack Overflow about setting a static enum inside a TypeScript class, I decided to create my own enum and implement it as a static property in my class. Here is how I did it: /* Input.ts */ enum INPUT_TYPE { T ...

Struggling to update TypeScript and encountering the error message "Unable to establish the authenticity of host 'github.com (192.30.253.113)'"

While attempting to update my version of TypeScript using npm, I ran into an issue when trying to execute the following command: localhost:Pastebin davea$ npm install typescript/2.8.4 --save-dev The authenticity of host 'github.com (192.30.253.113)&a ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it still results in the same error. ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...

The type Observable<any> cannot be assigned to Observable<any> type

I am currently working with angular 5 and ionic 3. I have defined an interface: export interface IAny { getDataSource: Observable<any>; } Components that implement this interface must have the following method: getDataSource () { return ...

What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form. How can I trigger val ...