The juvenile entity does not align with the foundational entity [typescript]

After setting "strict": true in my tsconfig.json, I encountered compiler errors when attempting to run the code. To replicate and explore this issue further, you can try running the following code snippet. The problem arises when the child class is deemed incompatible with the base class. Could there be a potential solution that I am overlooking or perhaps an error in my approach?

export class AbstractDto {
    id: string;
    createdAt: Date;
    updatedAt: Date;

    constructor(entity: AbstractEntity) {
        this.id = entity.id;
        this.createdAt = entity.createdAt;
        this.updatedAt = entity.updatedAt;
    }
}

export abstract class AbstractEntity<T extends AbstractDto = AbstractDto> {
    id: string = '';
    createdAt: Date = new Date();
    updatedAt: Date = new Date();

    abstract dtoClass: new (entity: AbstractEntity, options?: any) => T;
}
export class UserEntity extends AbstractEntity<AbstractDto> {
    firstName: string = '';
    one: string = '';

    dtoClass = UserDto;
//  ^^^^^^^^ - Property 'dtoClass' in type 'UserEntity' 
//             is not assignable to the same property in base type 'AbstractEntity<AbstractDto>'.
}

export class UserDto extends AbstractDto {
    one: string = '';

    constructor(user: UserEntity) {
        super(user);
//            ^^^^ - Argument of type 'UserEntity' 
//                   is not assignable to parameter of type 'AbstractEntity<AbstractDto>'.
        this.one = user.one;
    }
}

Answer №1

Upon investigation, I have successfully replicated the issues you mentioned. However, after making some adjustments to your code, I am pleased to report that the revised version below appears to be error-free—at least, on my local machine.

export class AbstractDto {
    id: string;
    createdAt: Date;
    updatedAt: Date;

    constructor(entity: AbstractEntity) {
        this.id = entity.id;
        this.createdAt = entity.createdAt;
        this.updatedAt = entity.updatedAt;
    }
}

// The use of 'Generic' is unnecessary as we will utilize the "typeof" keyword (as indicated below).
// export abstract class AbstractEntity<T extends AbstractDto = AbstractDto> {
export abstract class AbstractEntity {
    id: string = '';
    createdAt: Date = new Date();
    updatedAt: Date = new Date();

    // abstract dtoClass: new (entity: AbstractEntity, options?: any) => T;
    abstract dtoClass: typeof AbstractDto; // Utilize "typeof" instead
}

// It is advised to remove the generic declaration here too since it has been eliminated from the "AbstractEntity" class above.
// export class UserEntity extends AbstractEntity<AbstractDto> {
export class UserEntity extends AbstractEntity {
    firstName: string = '';
    one: string = '';

    dtoClass = UserDto;
}

export class UserDto extends AbstractDto {
    one: string = '';

    constructor(user: UserEntity) {
        super(user);
        this.one = user.one;
    }
}

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 error occurred in TSX + React: Uncaught TypeError - The property 'setState' cannot be read since it is undefined in Menu.handleClick

Currently, I am utilizing [email protected] along with react and react-dom @15.6.2. Encountering a troublesome issue that I can't seem to debug: Uncaught TypeError: Cannot read property 'setState' of undefined at Menu.handleClick. Thi ...

Having trouble retrieving the JSON data from the getNutrition() service method using a post request to the Nutritionix API. Just started exploring APIs and using Angular

When attempting to contact the service, this.food is recognized as a string import { Component, OnInit } from '@angular/core'; import { ClientService } from '../../services/client.service'; import { Client } from '../../models/Cli ...

Ensure that Angular resolver holds off until all images are loaded

Is there a way to make the resolver wait for images from the API before displaying the page in Angular? Currently, it displays the page first and then attempts to retrieve the post images. @Injectable() export class DataResolverService implements Resolv ...

Exploring the functionalities of arrays in Typescript: A beginner's guide

Currently, I am working on a react project and building a store within it. Below is the code snippet I have implemented: import React, { useReducer, useEffect } from 'react'; import { v4 as uuid } from 'uuid'; import { Movie, MoviesAct ...

What is the reason that the command `npx create-react-app my-app --typescript` is not providing me with the expected TypeScript files?

I used the command npx create-react-app my-app --typescript to create my React project, but it seems like I still ended up with the default JavaScript boilerplate files. I was expecting to see files with a .tsx or .ts extension and use import * from as R ...

Error: The variable "document" is not defined in the context of NextJS TypeScript

Here is the import trace for the requested module: ./app/StarrySky.tsx ./app/resume/page.tsx ✓ Compiled in 425ms (711 modules) ⨯ app\StarrySky.tsx (9:4) @ document ⨯ ReferenceError: document is not defined Trying to set const vw equal to the ma ...

Utilizing Rxjs to transform an array of objects

My goal is to map an array of objects. Currently, I have the following code: return this.service.post(url, payload, this.httpOptions) .pipe( map((obj: any, index) => [({ ...obj, val1: obj[index].val1.id, v ...

Transferring object information to Backand using Ionic 2

I have developed a signup page using Ionic 2. In this signup page, I have included a dropdown menu for users to select their blood type. However, I am facing an issue where the selected blood type is not being sent to the Backand database as expected. I&ap ...

Transmitting MQTT information through an application programming interface

In my project using Ionic React, I am developing an application to showcase temperature data. To achieve this, I have established an API that transmits MQTT temperature information and utilize Axios for data retrieval. Despite my efforts, I am encountering ...

Ways to transfer information from the parent component while the component is repeatedly utilized on the page

Consider the following situation within Angular 6: There is one upload component that is being utilized twice on the same page. By clicking the add button on any upload component using a behavior subject, data specific to that upload component can be obt ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

Utilizing an Angular component for multiple purposes

For my Angular app, which is component-based and uses Angular version 1.5.5 with TypeScript, I have a header component that includes a country dropdown. This header component is used across multiple pages. However, when a country is selected from the dropd ...

The ngOnInit child function fails to activate when trying to assign a fresh object

On the parent page, I am passing user data to a child component in this way: <ng-container *ngIf="leaderboard"> <app-leaderboard-preview [user]="user" (click)="goToLeaderboard()"></app-leaderboard-preview> </ng-container> In t ...

Enhancing validation in Express with custom Typescript types for validation in Express Validator

I encountered an error while using the custom method of the express validator Issue: Argument of type '(userDoc: User | null) => Promise<never> | undefined' is not assignable to parameter of type '(value: User | null) => Promise ...

What are the best ways to handle data using the .pipe() function?

Looking to optimize an Angular component Typescript function that returns an Observable<book[]>. The logic involves: If (data exists in sessionStorage) Then return it Else get it from remote API save it in sessionStorage return it End ...

Implementing MouseEvents in Typescript React without having to pass them down to child elements

Is it possible to use Mouse Events on a whole React Element without having to pass it to a child element? I have been passing my handleEvent function to several functional components and now I want to know if it can be done without causing a TypeScript err ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Incorporate new class into preexisting modules from external library

I am currently working on expanding Phaser by incorporating a new module called Phaser.Physics.Box2D. While Phaser already utilizes this module internally, it is an additional plugin and I am determined to create my own version. TypeScript is the language ...

Encountering an error in a map operation does not hinder the subsequent map operation from being carried out

Within my angular application, I have implemented a Login method that performs the following tasks: login(username, password): Observable<User> { let data = new URLSearchParams(); data.append('username', username); data.append(' ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...