What is the process of 'initializing' an object in TypeScript?

Is it possible that retrieving a json from a mongodb database and casting it does not trigger the typescript constructor? What could be causing this issue?

I have a Team class

export class Team {
    transformations: { [transformationId: string]: Transformation }
    typeTrees: { [ttMakerId: string]: TTMaker }

    constructor() {
        console.log('NewTree constructor called')
        this.transformations = {}
        this.typeTrees = {}
    }
}

I am downloading a json data, which should match the structure of the Team type:

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<string | null>
) {
    const transformationId = req.query.transformationId as string
    const text = req.query.text as string
    try {
        const { mongoClient } = await connectToDatabase()
        const db: Db = mongoClient.db('datamapper')
        const collection = db.collection<Team>('team')
        const team: Team | null = await collection.findOne({
            name: 'responsive',
        })

However, when I set a breakpoint at the constructor of Team, it doesn't get triggered. Why is that happening?

https://i.sstatic.net/eUV8W.jpg

Answer №1

let dataOfTeam = await collection.findOne({ name: 'responsive' });
let newTeam = Object.assign(new Club(), dataOfTeam);

By executing this code, a fresh instance of the Club entity will be generated using the new keyword, then the obtained information will be assigned to it via Object.assign(). Consequently, this process should activate the constructor function.

Answer №2

In order to create an instance of the Team class, you will need to utilize the new operator as demonstrated below:

const myTeam: Team = new Team();

When using the new operator, it calls the constructor function of the Team class.

I trust this explanation is beneficial to you!

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

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...

What is the best way to add an external .js file to my Angular 2 application?

I'm currently working on a project using Angular 2's TypeScript API along with webpack to develop a web application. However, I've encountered an issue where one of my components needs to utilize functions from an external .js file that is p ...

The error message indicates a change in the binding value within the template, resulting in an

This is the structure of my component A : <nb-tab tabTitle="Photos" [badgeText]="centerPictures?.pictures?.length" badgePosition="top right" badgeStatus="info"> <app-center-pictures #centerPictures [center]="center"> ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

How to prevent unnecessary new instances from being created by the Inject() function in Angular

Can someone please clarify if the inject() function provides different instances of a service? I suspect this might be why my code is not functioning as expected. Let's examine the code snippet below: { path: 'recipes', comp ...

Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below: component.ts emails: string[] = []; constructor(public userService: UserService) {} // Function ...

Show a condensed version of a lengthy string in a div using React TS

I've been tackling a React component that takes in a lengthy string and a number as props. The goal of the component is to show a truncated version of the string based on the specified number, while also featuring "show more" and "show less" buttons. ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

Angular 13: Issue with displaying lazy loaded module containing multiple outlets in a component

Angular version ^13.3.9 Challenge Encountering an issue when utilizing multiple outlets and attempting to render them in a lazy module with the Angular router. The routes are being mapped correctly, but the outlet itself is not being displayed. Sequence ...

Configuring NextUI with Next.js and TypeScript - CssBaseline component not found in @nextui-org/react package

Struggling to find reliable resources for installing Next.js and NextUI with the latest versions? The most helpful guide I found was this one, but not everything aligns perfectly. The guide instructs me to import CssBaseline like this: import { CssBaselin ...

Exploring the use of two different array types in the useState hook with TypeScript

Working on a movie gallery project, I am utilizing an API to download movies and TV series. They are then displayed in a Row component where users can click on thumbnails to open them. The challenge arises with TypeScript, as the useState array can receiv ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

I seem to be failing at properly executing Promises... What crucial element am I overlooking in this process?

Within my project, there exists a file named token.ts which contains a function that exports functionality: import * as jwt from 'jsonwebtoken'; import { db, dbUserLevel } from '../util/db'; export function genToken(username, passwor ...

Transform a nested array of objects into a distinct set of objects based on the data in JavaScript or TypeScript

I have a unique situation where I am dealing with a double nested array of objects, and I need to restructure it into a specific array format to better align with my table structure. Here are the current objects I'm working with and the desired resul ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...