Using a class as a property type in another class in TypeScript: A beginner's guide

I am a beginner in TypeScript and I have defined some classes. These classes are being used as types for the properties of other classes, like so:

FileOne.ts

export class A {
   propertyOne: string;
   propertyTwo: string;
}

Now, in another file (filetwo.ts), I have another class B:

FileTwo.ts

import { A } from './FileOne';
export class B {
    myProperty: A;
    mySecondProperty: string;
}

I have created an instance of class B in a different file with the following code:

MyApp.ts

import { B } from './FileTwo';
export class C {
    let myObj: B = new B();
    myObj.myProperty.propertyOne = 'hello';
    myObj.myProperty.propertyTwo = 'world'';
    console.log(myObj);
 }

However, I encountered an error when trying to set the property of A through B:

Cannot set the property "propertyOne" of undefined

I'm confused as I expected this behavior to be similar to Java. Could you please explain why I am facing this issue and suggest the correct approach? I would appreciate not just a solution to the problem, but also an explanation.

Answer №1

Although you have correctly specified the type of your myProperty member, it seems that this variable is not being initialized when declared. As a result, you are attempting to set a property propertyOne on an undefined variable within your instance of B.

To ensure proper initialization, it is necessary to manually initialize the variable within your B class:

export class B {
  myProperty: A;
  constructor() {
    this.myProperty = new A();
  }
}

Answer №2

myObject.myProperty is of type A, but it has not been defined yet. It is recommended to initialize it first:

myObject.myProperty = new A();

After initializing, you can proceed to use it accordingly.

Answer №3

Although it may be beyond the immediate topic, I encountered similar issues while working with VueJs as well. Building on Andreas Jägle's response, a slight adjustment resolved my problem, requiring the addition of super(); in my class constructor.

importmodule.ts

import Vue from 'vue'; 
import { Component, Prop } from 'vue-property-decorator'; 
import { MyProfile } from '../../data';

interface CurrentUser {
    name: string;
    title: string;
    groupName: string; }

@Component 
export default class Profile extends Vue {
    profile: MyProfile;

    constructor() {
        super();
        this.profile = new MyProfile();
    } }

data.ts

export interface IPro {
    name: string;
    title: string;
    groupName: string;
}

export class MyProfile implements IPro {
        name = "User";
        title = "Title";
        groupName = "Group";
    }

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

Creating a Utils class in Vue.js with seamless access to Vuex through this.$store

I have a situation where I need to retrieve state from the Vuex store using this.$store. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution. Here is my plugin implementation: index.ts i ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

Running the "npm start" command in Next.js results in the error message: "Unable to execute dev server: Error: [object Object]"

Just delving into the world of Next.js and feeling a bit lost with debugging. You can view the code here. Background: I went through the Amplify Next.js tutorial (although Amplify might not be the issue here), but opted for TypeScript as my language choic ...

Is it possible to set up tsc to compile test specifications specifically from a designated directory?

I have been working on integrating e2e tests into an Angular project that was not originally set up with @angular-cli, so I have been manually configuring most of it. Currently, I am trying to define a script in the package.json file to transpile only the ...

What steps should I take to modify the date format to "dd / mm / yy"?

When using 'toISOString ()' in JavaScript, it appears as shown in photo 2. How can I modify this format? Note: I am working with AngularJs. Image 1 is located in list.component.ts Additional documents: Image 1 Image 2 Image 1: formatDate(e) ...

Encountering unexpected null values post-service invocation in Angular 2

I have encountered an issue in Angular 2 where a variable is returning undefined. The problem arises when a function calls a service to initialize a variable, which is then used in another function to make a get HTTP request. However, the get request fails ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

Is there a method to categorize an array of objects by a specific key and generate a new array of objects based on the grouping in JavaScript?

Suppose I have an array structured like this. It contains objects with different values but the same date. [ { "date": "2020-12-31T18:30:00.000Z", "value": 450 }, { "date": "20 ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

JavaScript - Saving an array of objects to an .xlsx file with various header rows that are merged

I am faced with the challenge of recreating an Excel file that was manually created programmatically. I currently have a node.js(TS) service that exports data into a csv file, but the formatting is not as desired. After some research, I couldn't find ...

Unable to connect Formik Validation Errors to an array of objects

I am working on a form that consists of two fields: a boolean value and an array of objects. When the boolean value is true, the array becomes a required field. The array contains two string fields - one is required and the other is not. Validation Schema ...

Having trouble with Next.js 13 GitHub OAuth integration - it keeps redirecting me to Discord instead of signing me in

There's a perplexing issue troubling my application... The implementation of OAuth 2 with GitHub, Discord, and Google is causing some trouble. While Google and Discord authentication works smoothly, attempting to sign in via GitHub redirects me to Di ...

Can you explain the significance behind this code: { [productId: string]: ObjectType }?

I'm currently learning TypeScript and here is a snippet of source code: export class ShoppingCartItem{ $key:string; title:string; imageUrl:string; price:number, quantity:number, } ...... ...... itemsMap: { [productId: string]: ShoppingCartI ...

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

Concealing a banner on a specific page

I am currently trying to hide a banner on a specific page. I have successfully hidden the banner on all pages except for one that has a unique ID. Additionally, I am working with a dynamic folder called [content]. import { useRouter } from "next/rou ...

Tips for reducing a discriminated union by using the key value of a Record

I am working with a union type that has a discriminator property called "type". I then define a Record<> where the keys are the "type" property values. How can I specify the second generic parameter of the Record (Record< , this param>) so tha ...

Flipping through different pages showcasing the identical model

Exploring the world of Angular (currently Angular5) has led me to a query regarding page navigation within the same model. Consider an older project built on AngularJS. Let's take the example of a model called Customers. The pages related to this mod ...

The data type 'FetchData[]' cannot be assigned to type 'string' in Ionic React with Typescript

How can I store the response.body, which is a base64 string of a file, into a String variable? https://i.sstatic.net/JTkU7C2C.png fetchCustom(store.apiURL, { trtyp: 'file_download', seskey: store.userSessionKey, ...

A TypeScript class transferring data to a different class

I have a set of class values that I need to store in another class. function retainValues(data1,data2){ this.first = data1; this.second = data2; } I am looking for a way to save these class values in a different class like this -> let other = N ...