Tips for creating class variables with default values that are more complex than simple flat values

Creating a simple flat class like this functions smoothly:

class Test {
 company_name: string = "";
 company_id: number = 0;
 company_website: string = "";
}

When I instantiate it with let product = new Test(), everything works as anticipated, and product is initialized with the default values.

Is there a way to achieve the same outcome for non-flat class variables? Ideally, it should function similar to this example (which currently fails):

class Test {
  companyData: {
    company_name: string = "";
    company_id: number = 0;
    company_website: string = "";
  }
  productData: {
    category_id: number = 0;
    product_name: string = "";
    price: {
      price_in: number = 0;
      price_out: number = 0;
    }
  }
}

The error message in VSCode reads

A type literal property cannot have an initializer
. For my specific scenario, it's crucial that all variables are initialized and can be assigned default values.

Answer №1

You have to define the Types, without setting the values of the properties. The syntax is incorrect in any case.

Here's a suggested revision:

class Test {
  public companyData = {
    company_name: '',
    company_id: 0,
    company_website: ''
  };
  public productData = {
    category_id: 0,
    product_name: '',
    price: {
      price_in: 0,
      price_out: 0
    }
  };
}

If you want them to be Typed (which is recommended), use interfaces:

interface CompanyData {
  company_name: string;
  company_id: number;
  company_website: string;
}

interface ProductData {
  category_id: number;
  product_name: string;
  price: Price;
}

interface Price {
  price_in: number;
  price_out: number;
}

class Test {
  public companyData: CompanyData = {
    company_name: '',
    company_id: 0,
    company_website: ''
  };
  public productData: ProductData = {
    category_id: 0,
    product_name: '',
    price: {
      price_in: 0,
      price_out: 0
    }
  };
}

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

How can I remove a row from a mat table using Angular?

Having trouble implementing *ngFor in my angular mat table, seeking guidance from someone with more expertise? I am trying to delete a row within an array using a button and display it on my table, but encountering issues. I intend to utilize *ngFor to sh ...

How to extract a value from [object object] in Angular4

In my previous question, I shared the code below: getUserRole() { const headers = new Headers(); headers.append('Authorization', `Bearer ${this.getToken()}`); console.log(this.getToken()); const options = new RequestOptions({ headers: he ...

How to leverage async/await within loops in Node.js for optimized performance and efficiency

Hey there, I'm working on my nodejs api where I need to fetch data inside a loop and then perform another loop to save data in a different table. Can anyone guide me on how to achieve this? Below is a snippet of what I have attempted so far without su ...

Encountered an error in TypeScript and Webpack 4: Module Build failed due to an Unexpected token, expecting a ","

Just a heads up, I've already gone through all similar questions The babel config in my package.json: "babel": { "presets": [ [ "@babel/preset-env", { "useBuiltIns": "usage" } ], [ "@ba ...

You must add the module-alias/register to each file in order to use path aliases in

I am currently utilizing typescript v3.6.4 and have the following snippet in my tsconfig.json: "compilerOptions": { "moduleResolution": "node", "baseUrl": "./src", "paths": { "@config/*": ["config/*"], "@config": ["config"], ...

Tips for integrating and utilizing the MSAL (Microsoft Authentication Library for JavaScript) effectively in a TypeScript-based React single page application

Issue I'm encountering difficulties importing the MSAL library into my TypeScript code. I am using the MSAL for JS library with typings in a basic TypeScript/React project created using create-react-app with react-typescript scripts. As someone who i ...

Why does the playwright's onEnd() results not include the duration as specified in the documentation? What am I overlooking?

The built-in onEnd method can have a results object that is accessible within the function. According to the documentation here, this object should include the property duration, which represents the time in milliseconds. However, when I attempt to access ...

What is the best way to retrieve the Base64 string from a FileReader in NextJs using typescript?

My goal is to extract a string from an object I am receiving in the response. const convertFileToBase64 = (file: File): Promise<string> => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.r ...

Ways to determine the current active tab in React are:

Currently, I am facing an issue with my code involving two tabs. Upon clicking on the second tab, I want to display a specific message. However, I am struggling to determine when the second tab is selected. The main problem lies in the fact that the selec ...

Is there a way to automatically scroll 50 pixels down the page after pressing a button?

Is there a way to make my page scroll down in Angular when a button is clicked? I attempted to use this code, but it didn't have the desired effect. What is the best method for scrolling the page down by 50px? window.scrollBy(0, 50); ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

Serious issue: a dependency request is an expression (Warning from Angular CLI)

I am currently exploring the dynamic loading of lazy child routes within a lazy routing module. For example: const serverResponse = [ { path: "transaction", children: [ { path: "finance", modulePath: &qu ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

The type 'string' does not share any properties with the type 'CSSProperties'

How can I resolve the issue of Type 'string' has no properties in common with type 'CSSProperties'? const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Angular Date format

When I retrieve a date value from my angular interface, it appears in the following format. Sat Dec 29 2018 08:42:06 GMT+0400 (Gulf Standard Time) However, when I receive the data from an API, the JSON result looks like this. How can I make it the same t ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

What could be the reason behind the material table not populating with data from the source, despite the service returning an array?

Currently, I am utilizing a mean stack in order to craft a bug tracking system. The issue arises when my express.js service returns an array of issues, which I assign to another array that functions as the dataSource for mat-table. However, despite the ar ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Guide on exporting Excel data using Angular and TypeScript

My project involves managing a table of information that includes fields for FirstName, LastName, PhoneNumber, Age, and Date. I've created a function that allows me to export the data to an Excel file, but I only want to export specific fields like Fi ...