What causes Typescript to accept some objects and reject others?

I find the behavior of the Typescript compiler quite perplexing in relation to this code. I am using JSON.parse to populate a class instance from another class instance's output of stringify.

It seems like the return value of JSON.parse is simply a regular object. When I pass this object to a load method, it functions properly, but the compiler throws an error saying that it can't locate the property. Strangely, if the object is re-parsed (i.e. JSON.parse(JSON.stringify(obj))) within the load method, there are no longer any complaints from the compiler. What exactly makes one instance "unknown" to the compiler while the other is recognized? Is there truly a distinction between these two instances or is it some sort of type checking hiccup?

class Address {
    street = "12 Main Street"
    city = "Fooville"

    load(obj: object) {
        this.hello();
        this.street = obj.street;  //   <-- "Property street does not exist on type object
        this.city = obj.city;      //   <-- "Property city doe snot exist on type object
        this.hello();

        let parseObj = JSON.parse(JSON.stringify(obj));

        this.street = parseObj.street;  // <-- no complaints
        this.city = parseObj.city;      // <-- no complaints
        console.log(parseObj.constructor.name);
        console.log(obj.constructor.name);
    }
    hello() {
        console.log(`My address is ${this.street}, ${this.city}`);
    }
}

let foo = new Address();
foo.city="Raleigh"
let jstring = JSON.stringify(foo);
let goo = new Address();
let jparse = JSON.parse(jstring);
goo.load(jparse);
goo.city = "Denver"
goo.hello();
foo.hello();

console out:

My address is 12 Main Street, Fooville
My address is 12 Main Street, Raleigh
Object
Object
My address is 12 Main Street, Denver
My address is 12 Main Street, Raleigh

Answer №1

The function JSON.parse now returns any type of data which is the reason why you are not encountering any errors anymore. You can view the full signature here.

The syntax for JSON.parse is: 
JSON.parse(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined): any

If you use:

let parseObj = JSON.parse(JSON.stringify(obj));

It is essentially the same as:

load(obj: any) {
  // ...
}

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

Tips for centering an Angular mat prefix next to a label in a form field

Hey everyone, I need some help with aligning the prefix for an input with the mat label. Can anyone suggest a way to adjust the mat prefix so that it lines up perfectly with the mat label? Any assistance or ideas would be greatly appreciated. Here is the ...

Identify a singular instance of a union in Typescript without prejudice

Can options of a union be differentiated one by one, and if no case matches a discriminated interface, can it fallback to another interface? enum ActionType { add = 'add', remove = 'remove', modify = 'modify', } i ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

The parameter 'To' cannot be assigned the argument of type '{pathname: string; shipment: TShipment;}'

Is there anyone who can assist me with a Typescript issue I'm currently facing? Upon running tsc in my project, I encountered the following error: I am getting the error saying that 'Argument of type '{ pathname: string; item: Item; }' ...

"Download content for offline viewing without the need to create a player object using shaka player

Class: shaka.offline.Storage This class includes a constructor. new Storage(player) Class: shaka.Player This class also has a constructor. new Player(video(non-null), opt_dependencyInjector(opt)) However, my goal is to save a video URL without a vide ...

A step-by-step guide on customizing the background color of a Dialog in Angular Material (Version 16)

I've been attempting to modify the background color of my Angular Material Dialog by utilizing the panelClass property in the MatDialogConfig. Unfortunately, I'm encountering a partial success. I am aiming to set the background color as red (jus ...

Swap references between two components at the same level

There are two instances of custom-component spawned by a shared parent with distinct data, each displayed as a tab in the mat-tab-group. <mat-tab-group> <mat-tab label="TAB1"> <ng-template matTabContent> <custom-componen ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

Implementing an Angular function to close a window when clicking outside of it

I was browsing YouTube and came across a tutorial on how to create a directive that closes a window when clicking outside of it. However, I'm facing an issue with implementing this in my project. I built a simple to-do list application with the abilit ...

Switch on a single component of map array utilizing react and typescript

I am currently working on mapping a reviews API's array and I encountered an issue where all the reviews expand when I click on "read more" instead of just showing the clicked review. Since I am new to TypeScript, I'm not sure how to pass the ind ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Exploring NestJs: A comprehensive guide to testing response controllers

I am looking to use Jest to test the responses from my API. This method is from my controller. @Post('send-banana') async sendBanana( @Body() request: BananaRequest, @Res() res: Response, ) { const responseCodeService = await th ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

Issues arise with Typescript Intellisense in Visual Studio Code causing it to stop functioning

I'm currently exploring the world of building desktop applications using Electron and Typescript. After selecting Visual Studio Code as my IDE, everything was going smoothly and I managed to successfully load a sample HTML file into Electron. However ...

Develop a mapping system using enums that ensures compiler errors are enforced

I am struggling to enforce a mapping on an object in TypeScript. My goal is to define a type or interface that maps from ANIMAL_PLACE to ANIMAL_TYPE. I want the type to ensure that any object created with these mappings includes both the ANIMAL_PLACE and A ...

What is the best way to define a union type that encompasses all values within a field of an array?

I have a function that takes an array and a field parameter, but I want to restrict the field's type to a union type that describes all the values of the fields in the array. Here's an example: interface item { name: string, value: number ...

Tips on how to properly format a DateTime String

I need help with formatting a DateTime string retrieved from an API where it is in the format of YYYY-MM-DDTHH:MM:SS +08:00 and I want to change it to DD-MM-YY HH:MM getDataFromApi(res) { this.timestamp = this.timestamp.items[0].timestamp; console ...