Creating a new model in TypeScript may encounter a declaration issue with getting

I may just be overlooking something, but I have the following model:

import { Brand } from './brand';
import { Plan } from './plan';
import { Venue } from './venue';

export class Subscription {
  id: number;
  brandId: number;
  planId: number;
  venueId: number;
  state: number;
  startDate: string;
  endDate: string;
  rolling: boolean;
  overridePlan: boolean;
  productCount: number;
  price: number;
  termsAgreed: boolean;

  brand?: Brand;
  plan?: Plan;
  venue?: Venue;

  get stateName(): string {
    switch (this.state) {
      case 0:
        return 'Reserved';
      case 1:
        return 'Pending';
      case 2:
        return 'Active';
      case 3:
        return 'Cancelled';
      case 4:
        return 'Expired';
      default:
        return 'Unknown';
    }
  }
}

In this model, I am using a getter to retrieve the stateName. However, when attempting to create a new model:

const model: Subscription = {
    id: 0,
    brandId: 0,
    planId: 0,
    venueId: 0,
    state: 0,
    startDate: '',
    endDate: '',
    rolling: true,
    overridePlan: false,
    termsAgreed: false,
    price: 0,
    productCount: 0,
};

An error is raised indicating that stateName is missing in the new model. Shouldn't it be automatically populated by the getter?

The error message states:

Property 'stateName' is missing in type '{ id: number; brandId: number; planId: number; venueId: number; state: number; startDate: string; endDate: string; rolling: true; overridePlan: false; termsAgreed: false; price: number; productCount: number; }' but required in type 'Subscription'.

Is it really necessary to specify it manually?

Answer №1

It's important to remember that when creating a new instance of the Subscription object, all getters and setters from the class will not be included in the new instance.

To properly create a new instance with all necessary properties, you can utilize the object.assign() method like so:

const item: Subscription = Object.assign(new Subscription(), {
    id: 0,
    brandId: 0,
    planId: 0,
    venueId: 0,
    state: 0,
    startDate: '',
    endDate: '',
    rolling: true,
    overridePlan: false,
    termsAgreed: false,
    price: 0,
    productCount: 0,
});

Answer №2

In TypeScript, classes are categorized into two namespaces: value and type. The type signature of the class you were using is essentially the same as defining an interface like the one below:

Product {
  name: string;
  price: number;
  category: string;
  stock: number;
  onSale: boolean;
}

To make your code work, you must first create an instance of the class using the new keyword and then set values for its properties:

const item = new Product();
item.name = "Example";
...

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

The module '@angular/cdk/clipboard' cannot be located at this time

I recently encountered an error after installing Angular Material in my project. Here is a snippet from my package.json file. I am using Angular 8 and have attempted to modify the versions of Angular Material components. "dependencies": { & ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

Verify if the reactive form retains its original values

In my Angular 6 project, I have a reactive form with numerous fields including dropdowns and number inputs. Some of these fields start with empty values while others default to true. Users are allowed to select any combination of fields, making it impossi ...

Accessing items in a list generated by ngFor in Angular 6 using checkboxes

I need help with displaying an array using ngFor in Angular (specifically Angular 6). I want to be able to select certain cars by checking a checkbox, and then purchase the selected cars when I press a button. Although the list and checkboxes display corr ...

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...

Angular project service file experiencing issues with TypeScript string interpolation functionality

Here is the code snippet for a service in an Angular project: @Injectable() export class FetchDataService { fetch(link){ console.log('This is a ${link}'); } } In my component, I am invoking this method with a string parameter. Upon che ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Is the async pipe automatically unsubscribing from an observable that is defined in a service and referenced in a component variable?

Within my service, I have a BehaviourSubject declared and I reference it with a variable in another component. In the view of that component, I subscribe to the subject using the said variable, as shown below: Service: public exampleSubjebt$ = new Behavi ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...

What are the best strategies for effectively overseeing employees within nativescript?

Currently, I am immersed in a project that combines nativescript-vue and typescript, requiring me to interact with workers. Even though I've delved into the NS documentation and implemented the recommended approach for working with workers, I'm f ...

Having trouble retrieving data from a local JSON file with Angular

I am attempting to retrieve data from a local JSON file in order to manipulate the data within the view. For example, if you choose UnitOne, the only available 'roles' you can select are 'role1', 'role2', 'role3', et ...

Trapped in a never-ending cycle caused by failing to dispatch an action within ngrx/effects

My current setup involves using Angular2, ngrx/store, and ngrx/effects for state management. I have encountered an issue where I am unable to display an error message when a specific action fails within an @Effects() block. Here is the problematic code sn ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

The combination of Autodesk Forge Viewer and React with TypeScript provides a powerful platform for developing

I'm brand new to React and Typescript, and I have a very basic question. In the viewer documentation, extensions are defined as classes. Is it possible to transform that class into a typescript function? Does that even make sense? For example, take th ...

Obtaining JSON Data from API using Angular 2 Http and the finance_charts_json_callback() Callback

Having trouble retrieving JSON data from this API: I'm unsure how to access the returned finance_charts_json_callback(). Currently, I am utilizing Angular 2's http.get(): loadData() { return this.http .get(this.url) .map((res) => ...

How come Angular8's routerLinkActive is applying the active class to both the Home link and other links in the navigation bar simultaneously?

Currently, I am facing an issue with routing in my project where the home tab remains active even when I click on other tabs. I have tried adding routerLinkActiveOption as a solution, but it doesn't seem to be working for me. <ul class="nav nav-ta ...

Managing a single Angular project with multiple apps that share common features: A guide

Imagine having multiple Angular 'apps' with similar features and functions, where one product needs to be customized for different clients with slightly varying needs. The challenge lies in developing within a single code base. Using feature mod ...

Unable to connect to 'formGroup' as it is not recognized as a valid property of 'form' within the component on the page

Currently, I am in the process of developing an app using Ionic. One of the pages I have created is called survey, and its corresponding component is known as SurveyPage. Within this page, there are various texts displayed along with a component tagged as ...

Best practices for managing backend errors with Next.js 14

Currently, I am developing a project in Next.js 14 and I have set up my API requests using fetch within a handler.tsx file as shown below: async function getPositions() { const response = await fetch( process.env.BASE_API_URL + "/positions?enabl ...