Deciding when to utilize an interface, when to avoid it, and when to opt for a constructor in Typescript for the creation of JavaScript arrays

Exploring the concept of JavaScript object arrays in TypeScript

In my current project, I am retrieving a JSON array from an observable. It seems that I can define and initialize the array without necessarily specifying an interface or type.

let cityList[]; // Is the value of cityList null at this point?
cityList[] = response;

Although using an interface is not mandatory, it is advisable for better compiler assistance similar to Java, right?

interface Blah{
city: string;
}

let cityList: Blah[];
cityList[] = response;

Alternatively, creating a constructor might be necessary if dynamically adding JavaScript objects to the array, is that correct?

Answer №1

After realizing my mistake, I now understand the correct approach to this.

Constructors are only necessary when adding or creating a new object that will be used within the code or transmitted over the network.

Instead of interfaces, I prefer using models.

For example, if I wanted to create a JavaScript object representing a city that only includes the city's name, it would look like this:

This code is written in TypeScript.

export class City{
  public name: string;

  constructor(name:string){
    this.name = name;
  }
}

In order to store these objects in an array, the array must have the correct type:

cityList:City[]; 

If the array is uninitialized, you can initialize it by assigning a value to the array or by setting it as an empty array like this.

cityList: City[] = [];

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

All-in-one Angular script and data housed within a single document

Context I want to design a personalized "dashboard" to assist me in staying organized. This dashboard will help me keep track of the issues I am currently handling, tasks I have delegated, emails awaiting response, and more. While I am aware of project ma ...

Enrich the returned result set by including additional data in Mongoose

Within a MEAN environment, utilizing mongoose, I am attempting to include additional data in the returned query result. The purpose is to add a 'thumbnail' field (which represents the calculated path of the thumbnail image) to each author in the ...

Using TypeScript or JavaScript, set object keys as fields of a class

I am looking for a way to update the properties of this class dynamically using an object export default class Foo { private accessKey: string; private workspaceId: string; private api: AxiosInstance; public bar: string; public name: s ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

Using requests.patch() will result in a 200 OK response, however, no updates

I'm currently working on integrating the requests module with the MailChimp API to update my contact list to "subscribed" status. To accomplish this, I am following the instructions provided in the official documentation. According to the guidelines, ...

Send a substantial item for display using Express Layout

Utilizing Express layouts to render my webpage upon accessing a specific route: The current project I am developing is an admin panel designed for editing a substantial table of data (imagine a website dedicated to managing thousands of product entries, fo ...

Having trouble with ReactJS updating the state in the correct format using moment?

In my ReactJS project, I am using a datepicker feature. However, I have encountered an issue where the state is not being updated with the selected date value after formatting it using moment.js. const [selectedDates, setSelectedDates] = useState([]) ...

Filtering out specific properties in an array using Angular

I am facing an issue with my Angular filter when inputting text for a specific list. initialViewModel.users = [ {user: 'Nithin',phone: 'Azus', price: 13000}, {user: 'Saritha',phone: 'MotoG1',price: 12000}, {user: ...

Encountering a 'Cannot use string as a HASH ref' error message while attempting to decode JSON in Perl using the JSON

Whenever I execute the following code: use strict; use JSON; $json_ref = $json->decode($json_data); After this, my $json_ref structure contains strings as hash refs. To visualize this, I use Data::Dumper like so: print STDERR "JSON: " . Dumper($json ...

Autocomplete's `getOptionLabel` function unexpectedly returned an object ([object Object]) instead of the expected string

Currently delving into the world of ReactJS and working with @mui controls, specifically a Multiselect Dropdown with autocomplete feature. Here is the child component causing me some trouble, displaying the following error message: "index.js:1 Materi ...

Is it possible to encounter the issue of "Context Lost" and "Importing multiple instances" in Three.js?

I am in the process of developing a 3D editor that allows users to manipulate a 3D scene and then view the result by pressing a "play" button. In order to display the output, I am utilizing an iframe. Below is the snippet of my HTML code: <iframe id=&qu ...

The type of the element is implicitly set to 'any' because the expression 'keyof IMyObj' cannot be used to index the type

Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution. I encountered a similar issue with my code and tried r ...

Should code in Vuejs be spread out among multiple components or consolidated into a single component?

After spending a significant amount of time working with Vue, I find myself facing a dilemma now that my app has grown in size. Organizing it efficiently has become a challenge. I grasp the concept of components and their usefulness in scenarios where the ...

The process of retrieving input field values from a table within an Angular reactive form

I am seeking a way to collect all input values found within the table rows inside a reactive form. Below is an explanation of my code. <form [formGroup]="productForm" (ngSubmit)="saveProduct($event)" novalidate> <mat-form-field appearance="outlin ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Is TypeScript necessary, or can I simply stick with ES6?

As a client developer using AngularJS in my daily job, we are considering transitioning to TypeScript. After researching TypeScript, I discovered that most JavaScript packages I require need definition type files. This can be inconvenient, especially whe ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...