When converting an object into a specific type, the setter of the target type is not invoked

Imagine a scenario with a class structured like this:

class Individual {
  private _name: string;

  get Name(): string { return this._name; }
  set Name(name: string) { this._name = name; }
}

Upon invoking

HttpClient.get<Individual>()
, it retrieves an object of type Individual but fails to trigger the setter for the object's properties.

An example illustrating this issue is that when casting, the setter is not executed, unlike regular object creation: https://jsfiddle.net/r175sLkh/

The underlying reason appears to be that during conversion from a JSON string, an anonymous object is first created and then cast into the desired object. In cases where there is a setter for a property, it gets overwritten by the basic type from the JSON object.

Therefore, the original Individual.Name() will be replaced by (anonymous).Name due to having the same name.

To ensure my setter functions as intended, I would need to manually iterate over the result from

HttpClient.get<Individual>()
and assign each property individually to a new instance of Individual...

So my query now is:

Is there a more efficient method to guarantee that a setter is activated when casting into the desired object without the need for manual conversion or assignment? (This inquiry does not focus on getter/setter functionality in TypeScript.)

Answer №1

One common misconception is that Typescript enforces execution time type safety, similar to languages like Java or C#. However, Typescript only provides compile-time type checking. For example, when using HttpClient.get<Person>(), it simply indicates your assumption that the returned object will conform to the Person class without actually enforcing it. There is no automatic casting of anonymous objects to specific types in Typescript.

Therefore, if you need to ensure a setter is executed, you must explicitly code for it as there is no built-in enforcement mechanism.

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

Navigating with Angular 4's router and popping up modals

I have an Angular 4 SPA application that utilizes the Angular router. I am looking to create a hyperlink that will open a component in a new dialog using Bootstrap 4. I am able to open modal dialogs from a function already. My question is, how can I achi ...

Can you retrieve the Angular Service Instance beyond the scope of an angular component?

Is it possible to obtain the reference of an Injectable Angular service within a generic class without including it in the constructor? I am exploring different methods to access the Service reference. For example: export class Utils { getData(): string ...

Trouble with maps not showing up and the console isn't showing any errors when using @react-google-m

Currently, I am facing an issue while trying to integrate Google Maps by following a blog post that provides instructions on next13 TypeScript. Despite reaching the point where the maps should be displayed, nothing appears on the screen. Surprisingly, ther ...

Learn how to creatively style buttons with dynamic effects using tailwindcss

My Desired Button: I have a Button component that can accept a variant prop. My goal is to have the button's className change dynamically based on the prop passed to it. Instead of using if/else statements for different buttons, I want to use a sing ...

What is the reason TypeScript struggles to automatically deduce assignments of identical object types?

Imagine a scenario with a simple code snippet to illustrate the issue: interface I { n?: number; s?: string; } const a: I = { n: 1, } const b: I = { n: 2, s: 'b', } const props = ['n', 's'] as const; for (const p ...

Experience the power of TypeScript in a serverless environment as you transform your code from

I have some JavaScript code that needs to be converted to TypeScript. Currently, I have two files: API_Responses.js const Responses = { _200(data = {}) { return { statusCode: 200, body: JSON.stringify(data), }; } }; module.export ...

How can I display images stored locally within a JSON file in a React Native application?

Hey everyone, I'm currently facing an issue with linking a local image from my images folder within my JSON data. Despite trying various methods, it doesn't seem to be working as expected. [ { "id": 1, "author": "Virginia Woolf", " ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...

Error message: "IAngularStatic type does not have property IScope" caused by Typescript Directives

I'm working on creating an Angular Directive using TypeScript to share a scope item. I created an interface that inherits from ng.IScope, but Visual Studio Code is showing me a warning: "Property IScope does not exist on type IAngularStatic". I am usi ...

The outcome of using Jest with seedrandom becomes uncertain if the source code undergoes changes, leading to test failures

Here is a small reproducible test case that I've put together: https://github.com/opyate/jest-seedrandom-testcase After experimenting with seedrandom, I noticed that it provides consistent randomness, which was validated by the test (running it multi ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

Tips for validating numeric fields that rely on each other with Yup

I am facing a challenge in setting up a complex validation using the library yup for a model with interdependent numeric fields. To illustrate, consider an object structured like this: { a: number, b: number } The validation I aim to achieve is ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

The data structure '{ recipe: null; }' cannot be matched with type 'IntrinsicAttributes & Recipe'

Currently, I am working on an app that integrates ChatGPT to fetch recipes based on user-input ingredients. After receiving the JSON response from CGPT, I aim to display a Recipe "Card" component. However, I encounter an error titled above when attempting ...

Enhance your TypeScript code using decorators with inheritance

Exploring the realm of Typescript decorators has led me to discover their intriguing behavior when combined with class inheritance. Consider the following scenario: class A { @f() propA; } class B extends A { @f() propB; } class C exten ...

Issue: Unable to locate 'child_process' in Angular 5

I am a newcomer to Angular, and I have encountered a requirement in my project to retrieve the MAC address of the user's system. To achieve this, I performed an NPM installation as shown below: npm install --save macaddress Next, I added the follow ...

Utilize Angular to initiate the transmission of attribute values upon a click event

My question may be simple, but I've been struggling to find an answer. How can I send attributes or item property bindings of an item through a click event in the best way? For example: <item class="item" [attr.data-itemid]="item.id ...

Toggle the visibility of an input field based on a checkbox's onchange event

I am facing a challenge where I need to display or hide an Input/Text field based on the state of a Checkbox. When the Checkbox is checked, I want to show the TextField, and when it is unchecked, I want to hide it. Below is the code snippet for this compon ...

Customize the format of data labels in horizontal bar charts in NGX Charts

I am currently using ngx-charts, specifically the bar-horizontal module. My goal is to format the data labels and add a percentage symbol at the end. I attempted to use the [xAxisTickFormatting] property, but it seems that my values are located within the ...

Types of Axios responses vary depending on their status codes

I am looking to create a specific type for axios responses based on the status code: types: type SuccessfulResponseData = { users: .... }; interface SuccessfulResponse extends AxiosResponse<SuccessfulResponseData, any> { status: 200; } ty ...