Array of Typed Objects in TypeScript

Here is the setter I created in TypeScript:

public set data(data: Array<Data>) {
  console.log(data[0].getterProperty);
  console.log(data[0] instanceof Data);
  console.log(typeof data[0]);
  this.setGridDataIfReady();
}

If data contains only one item, the output is:

undefined
false
object

I am confused as to why this is happening. Shouldn't the array only contain objects of type Data since that's what I specified?

Answer №1

It's important to remember that Typescript is a statically typed language that compiles down to JavaScript during runtime. This means that even though you define types in Typescript, the actual code being executed is JavaScript which can lead to unexpected behaviors.

While you may specify the type of an array as "Data" in your Typescript code, once transpiled, the runtime type becomes "Object". Unlike Java, where passing in an incorrect type would result in an Exception, Typescript does not provide this level of type safety during runtime.

If you truly want to ensure type safety and catch any errors at runtime, make sure that all entries in your array are created using the "new Data" constructor. By setting the constructor of the object, you can use the "instanceof Data" check to verify the type of each entry.

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

C# - Error message indicating that the index referenced is beyond the limits of the array when using lists of equal sizes in a

In my .NET project, I am developing a file downloader that uses Asynchronous tasks to download an array of files from a server. Despite ensuring that the Task[] and returned string[] have the same length, I encounter issues. Below is the method I have imp ...

The type '{ status: boolean; image: null; price: number; }[]' does not include all the properties required by the 'SelectedCustomImageType' type

While developing my Next.js 14 TypeScript application, I encountered the following error: Error in type checking: Type '{ status: boolean; image: null; price: number; }[]' is missing the properties 'status', 'image', and &apos ...

Avoid the import of @types definition without exports in TypeScript to prevent the error TS2306 (not a module)

I have spent a considerable amount of time trying to load a NodeJS library that has what I believe is a faulty type definition in the @types repository. The library in question is geolib and its types can be found in @types/geolib Although I am aware tha ...

Converting a C++ string array to JSON: A step-by-step guide

Recently, I embarked on the journey of incorporating Microsoft Cognitive Services using C++. In my implementation, there exists a C++ String array named faceIds. string faceIds[] ={ "29e874a8-a08f-491f-84e8-eac263d51fe1", "6f89f38a ...

Return the reference to an injected service class from the location where it was implemented

Is it feasible to return a reference from a component class with a custom interface implemented to the injected service class in my Angular 6 project? Here is an example of what I am aiming for. ServiceClass @Injectable() export class MyService { co ...

The error message "TypeError: text is not a function" is displayed when trying to utilize the text() method from either Blob

My current dilemma revolves around the usage of functions defined in the typescript lib.dom.d.ts file within my node.js express backend that is implemented using TypeScript. Specifically, I am encountering issues with the File/Blob interfaces where a File ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

The React component using createPortal and having its state managed by its parent will remain static and not refresh upon state modifications

I am facing a problem that can be seen in this live example: https://stackblitz.com/edit/stackblitz-starters-qcvjsz?file=src%2FApp.tsx The issue arises when I pass a list of options to a radio button list, along with the state and setter to a child compon ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

Inheriting Angular components: How can the life cycle hooks of a parent component be triggered?

So I'm working with BaseComponent and a number of child components that extend it: export class Child1Component extends BaseComponent implements OnInit, AfterViewInit In the case of Child1Component, there is no explicit call to super.ngAfterViewInit ...

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...

Type narrowing is ineffective for discriminated unions in most cases

Consider the type definition provided below: type A = { a: string } | { a?: undefined; b: string } This essentially means that if you include a, it should be the only property provided. If you do not include or have a as undefined, then you also need to p ...

Ensuring Type Compatibility Between Classes and Object Literals in TypeScript

When working with TypeScript, it is important to note that an object literal can be assigned to a class typed variable as long as the object provides all properties and methods required by the class. class MyClass { a: number; b: string; } // The co ...

Arranging an ArrayList in alphabetical order by fields containing non-English characters in Java

Trying to alphabetically sort an ArrayList of custom objects, I encountered an issue with non-English characters like á or é in the field used for sorting. Using Collections.sort() did not handle these characters correctly. Here's the approach I at ...

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

Storing a collection of models in Rails

In my array, I store instances of a model called SupplierPhone which looks like this: supplier_phone = SupplierPhone.where(:supplier_id => 1) supplier_phone = [#<SupplierPhone id: 1, supplier_id: 1, phone: "22423434234", created_at: "2011-07-21 00: ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Creating a hash map with the initial element of an array can lead to a potential null point exception

My code snippet looks like the following: char* talk[516] = {(char*)1}; #define testValue (*(int*)talk[0]) After running this code, I encounter a null pointer exception when trying to execute the following line of code. testValue = 0; Why am I getting ...

Having trouble injecting ActivatedRouteSnapshot into the component

Struggling to inject ActivatedRouteSnapshot into a component, encountering errors when trying to access query params. Here is the error stack trace: "Error: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?). a ...