Understanding Type Inheritance in TypeScript: Assigning a variable of a parent type to a variable of a child type

A scenario involves creating two distinct types:

export class GenericType {
  public id: string;
  public property: string;
  public name: string;
}
export class SpecificType extends GenericType {
  public value: string;
}

Let's say we have two variables A: GenericType and B: SpecificType. The objective is to transfer all values from A to B, as well as assign a specific value to B. However, manual assignment of each property from A to B is not desired.

let varA: GenericType = {
  id: '123',
  property: 'example',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
varB = varA; // Cannot directly assign here.
varB.value = 'new value';

Answer №1

Attempting to perform this action is not allowed:

let varA: GenericType = {
  id: '123',
  property: 'exmple',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
varB = varA;  <----- forbidden assignment.
varB.value = 'new value';

Instead, you can execute the following:

let varA: GenericType = {
  id: '123',
  property: 'exmple',
  name: 'example variable',
};

let varB: SpecificType = new SpecificType();
// The variation lies here:
varB = { ...varA, value: 'new value' }

The reason for not being able to assign varA to varB is because varA lacks a value. However, by utilizing the spread operator, you can combine all elements seamlessly.

Answer №2

Assigning the property value to a variable of type GenericType is not permitted. To work around this restriction, you can utilize a type assertion to specify that the variable is of type SpecificType:

let varB: SpecificType = new SpecificType();
varB = varA as SpecificType; // Now able to assign.
varB.value = 'new value';

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

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

Changing the value of an element in an array using typescript within an Angular context

I am currently working with Angular 5 and I have a task to update the array values based on the selectedMobile array. Below is my code snippet: const mobilelist = [ { 'key': 'apple', 'name': 'Apple', 'check ...

Changing Minute to HH:MM:SS in Angular 2

Instructions:- Minutes = 1220; Solution:- Time = 20:20:00; Is there a way to convert the minute value into a time format in Angular 2? ...

How to make an HTTP request in Angular 7 before the browser is closed

I'm attempting to trigger a POST HTTP request right before the browser closes. Essentially, I want to detect when the user closes the page and send a call, but the request isn't completing before shutdown. It seems like a traditional HTTP reque ...

Connect AngularFire to a specific object

I'm facing an issue with my Users.class where I need it to automatically map or bind after fetching data from Firebase. I've been trying to search for the right term but haven't found any information yet. import { Component, OnInit } from & ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Breaking down large reducer into smaller reducers

I am currently working on a feature reducer (slice reducer) called animals. My goal is to separate these reducers into categories such as mammals, birds, fishes, and more. Initially, I thought this would be a smooth process using the ActionReducerMap. How ...

Extending an External Object with Custom Properties in TypeScript

When working with an external library, I often find myself needing to add new properties to passed-in parameters. Instead of using (<any>conv.data) due to the compiler error Object is of type 'unknown', I'm curious if there's a mo ...

Struggled with setting up the WebSocket structure in typescript

Issue Running the code below results in an error: index.tsx import WebSocket from 'ws'; export default function Home() { const socket = new WebSocket('ws://localhost:1919/ws'); return ( <div>Home</div> ); } ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Ways to modify the datepicker format in Angular Material

I am currently facing an issue with the date format generated by the angular material datepicker...Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time) My requirement is to receive the date in either (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) format. Here is ...

What is the process for importing a TypeScript file as a library?

My customized personal "library," dubbed methlib and saved as a .ts file on my computer, contains a plethora of classes, interfaces, functions, and more that I frequently use and prefer to keep in one convenient location. The dilemma I face now is how to u ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

Enhance user interaction in Angular 13 by animating a selected element using just one animation block

I am currently working on a one-page website project to enhance my Angular skills, and I'm facing a challenge with animating multiple DOM elements using a single animation. Defining the animation for each element individually seems like a cumbersome a ...

Typescript: issue with type guard functionality not functioning properly

type VEvent = { type: "VEVENT"; summary: string; }; type VCalendar = { type: "VCALENDAR"; }; const data: Record<string, VEvent | VCalendar> = (...); array.map((id) => { return { id, title: dat ...

Having trouble accessing a downloaded image saved in local files from Amazon S3 using the AWS SDK in Node.js

I am currently using the node.js aws-sdk package to download files from s3 storage. However, when I download a jpeg image and save it as a local file, I am unable to view it. Is this the correct method for downloading jpeg images? public async downloadFi ...

Angular definitely typed does not convert into JavaScript

After installing TypeScript on my VS2013, I obtained the Angular 1.5 Definitely Typed from the NuGet package manager. Although angular.d.ts and its components do not generate angular.js file, when I create another TypeScript file like file1.ts, the file1. ...