Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results.

class X {
    y: string;
    get hi(): string {
        return `hi ${this.y}`;
    }
}

const a = new X();
a.y = 'bob';

const b = { y: 'ham' } as X;
const c = Object.assign(new X(), b);
document.write(a.hi); // outputs "hi bob"
document.write("<br>");

document.write((b.hi === undefined).toString()); // yields "true"
document.write("<br>");

Object.assign(b, X.prototype);
document.write((b.hi !== undefined).toString()); // generates "true"
document.write("<br>");
document.write(b.hi); // **shows "hi defined" -- seeking "hi ham"**
document.write("<br>");

document.write(c.hi); // produces "hi ham"
document.write("<br>");

Could there be something crucial missing in the conversion process for this setup to function correctly? Or should I stick with using Object.assign similar to how I handled it with

const c = Object.assign(new X(), { y: 'ham' });
?

Answer №1

Is it necessary to utilize Object.assign in a similar way as I am with the constant c = Object.assign(new X(), { y: 'ham' });

Absolutely.

However, it would be more ideal to incorporate it within the constructor:

class X {
    constructor(public y: string){}
    get hi(): string {
        console.log(this);
        return `hi ${this.y}`;
    }
}

Object.assign and class instances are not compatible. It is best used solely for object literals.

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

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

Struggle with Transmitting Information in Ionic 2

I have been working on an Ionic project that involves a JSON file with preloaded data. The initial page displays a list from which a user can select an item to view its content. However, I am encountering a "Response with status: 404 Not Found for URL" err ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

"Encountering issue with auto-import suggestions failing to appear in VS Code version 1.88.0

After installing the necessary libraries for MUI, I encountered an issue where basic components like Typography were not showing up in intellisense. Instead, it was displaying @mui/icons-material. You can view screenshots below: https://i.stack.imgur.com/ ...

ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When ...

Struggling with incorporating GlobalStyles in the app.tsx file

I have been working with next13 and styled-components. Initially, everything seemed fine in my file globalStyles.ts, and all was functioning perfectly. However, I started encountering errors related to the import of <GlobalStyles/>. Specifically, th ...

Utilize Typescript with React to efficiently destructure and spread objects

My goal is to maintain my child components as stateless (functional components). Therefore, I am in search of an efficient way to pass down the root component's state values to its children. For example, interface IState { a: string; b: number; ...

Union types can be used to constrain generic type parameters in Typescript

I'm working on a function uniqueIds(first: any[], second: any[]): number[] { let prop = first[0] instanceof Owner ? "OwnerId" : "BankId"; return _.unique( _.map( first, o => ...

Incorporate Ng-Survey multiple times within one component

Incorporating the ng-surveys template into my Angular application via has been successful. However, I encountered an issue where when using the template selector *ngFor to display multiple surveys on the same page, the browser treats all the surveys as id ...

Getting the most out of TypeScript Enum in Angular 6

I have a situation where I am storing the numeric value of an enum in my database and then displaying it in another part of the UI. Now, I need to retrieve the string value linked with that numeric value from the enum in a separate Angular component. Here ...

Increase by 30 minutes from the minimum value and decrease by 30 minutes from the maximum value in Ionic date time

Looking to add a customized Ionic date time picker with min and max capabilities. If the minimum time is selected, it should automatically add 30 minutes, while selecting the maximum time should subtract 30 minutes. Any suggestions on how to achieve this? ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Using TypeScript and Node.js with Express; I encountered an issue where it was not possible to set a class property of a controller using

I have a Node application using Express that incorporates TypeScript with Babel. Recently, I attempted to create a UserController which includes a private property called _user: User and initialize it within the class constructor. However, every time I ru ...

The compiler is still throwing missing return errors despite narrowing down all potential types

I encountered the following issue: Function is missing a closing return statement and its return type does not include 'undefined'. Here's my TypeScript code snippet: function decodeData( data: string | number[] | ArrayBuffer | Uint8Arr ...

Issues with the functionality of Angular Firebase Authentication Service

I am currently working on setting up an authentication service in Angular that will integrate with Google Firebase for a Login form. However, I have encountered an issue where including the service in the constructor of my LoginComponent prevents me from a ...