Tips on duplicating objects in TypeScript with type annotations

My goal is to inherit properties from another object:

interface IAlice {
  foo: string;
  bar: string;
};

interface IBob extends IAlice {
  aFunction(): number;
  anotherValue: number;
};

let alice: IAlice = {
  foo: 'hi',
  bar: 'bye'
};

let bob: IBob = Object.assign({}, alice); 

bob.anotherValue = 2;
bob.aFunction = (): number => {
  return 3;
}

Despite my efforts, I encountered a Typescript error.

I have considered making bob values optional or assigning values directly in Object.assign, but these solutions did not work due to the function aspect.

Is there a way for Typescript to recognize that the values will be defined?

Answer №1

When working with objects of type IBob, it is important to ensure that all fields required by IBob are defined. One way to achieve this is by creating the object as a fully formed IBob instance:

let bob: IBob  = Object.assign({
    anotherValue: 2,
    aFunction : (): number => {
        return 3;
    }
}, alice);

If you only want to partially initialize the object and have some fields missing, you can use Partial:

let bob: Partial<IBob> = Object.assign({}, alice);

bob.anotherValue = 2;
bob.aFunction = (): number => {
    return 3;
}

While making all fields optional using Partial may not always be suitable, it is a good option to consider. You can also make just the fields of IBob optional while keeping the ones from IAlice mandatory for more advanced typing:

let bob: Partial<Pick<IBob, Exclude<keyof IBob, keyof IAlice>>> & IAlice = Object.assign({}, alice);

bob.anotherValue = 2;
bob.aFunction = (): number => {
    return 3;
}

It is crucial to be specific about optional fields, especially under strictNullChecks, as you will need to explicitly check for null before accessing optional fields. If you choose to proceed with a type assertion, be cautious as it can lead to errors if not done accurately:

let bob: IBob = Object.assign({}, alice) as IBob;
// Or (but only if you are not in a tsx file)
let bob: IBob = <IBob>Object.assign({}, alice);

Answer №2

Here is a way to achieve it:

let person: IJohn | IMary = Object.assign({}, mary);

Now both interfaces IJohn and IMary can be assigned to the variable person.

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

Exploring the process of fetching and showcasing API responses through AJAX

I need to pass the value of my car to an API, which is retrieved from the HTML below. After that, I would like to send this value to the API using AJAX. Finally, I want to display all the models in the same way as I displayed the cars. $(document).r ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

Create a new CSS rule within a class, and remember to save the changes to

Upon opening page 1.html, I utilize JavaScript to dynamically add a background image to the body of the page. To achieve this, I use the following code: document.body.style.backgroundImage = "url(http://www.example.com/image.jpg)"; This code effectively ...

Adding animation to rows in ngx-datatable: A Guide

I am looking to stack the rows of my data table (ngx) one after the other in a vertical fashion. I want to incorporate [@datatableAnimation], but I'm unsure where to place it. When adding it to <ngx-datatable [@datatableAnimation]>, it only af ...

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

Testing TypeScript functionality within the Eclipse environment with unit tests

Is there a method to test TypeScript code on the Eclipse platform? I'm searching for something similar to JUnit, but most of the tools I've come across are geared towards Visual Studio. ...

Is there a way to transfer the chosen maximum and minimum price values to a JavaScript function within a select tag in HTML?

I have a search form that includes select options with two values. However, I want to have two select options for both the Max and Min price values. <input type="hidden" id="budget_min" name="filter_budget_min" value="0" /> <select onchange="upda ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

The website encountered an error in loading with the error message "ENOTFOUND" in Cypress

All my cypress tests were running smoothly until one day they all failed to visit the target site. The error message that I received was: cy.visit() failed trying to load: https://mywebsite.com/accounts/login/ We attempted to make an http request to this ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Arranging array elements according to the values in another array

I am working with an array of selections: var selections = ( JSON.stringify($('#approval').select2('data')) ); var selections = JSON.parse("[" + selections + "]"); When I use console.log with selections, the output is: https://i. ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Is there a method to automatically create .stories.ts files in Angular Storybook?

I am seeking a way to automatically create a .stories.ts file within a component folder after executing the command ng g component my-component. The desired outcome should resemble this structure: my-component -my-component.component.html . ...

What is the proper way to invoke express-validator within a middleware function?

I am facing a challenge in invoking the express-validator function from a middleware function. Although I can see that the execution is happening within the express-validator, validation does not seem to occur. The code snippet is provided below: router.g ...

Tips for avoiding $state refresh in Components unaffected by changes to $state.var?

We are currently utilizing Angular-ui-router for managing the state of our application. One issue we are facing is that every component refreshes when there is a change in the $state, even if it's a variable that has been updated and is not used or d ...

How can I identify the main text of a specific <MenuItem/> component in ReactJS Material-UI?

I've been working with the Material-UI Dropdown Menu component and I'm trying to figure out how to console log the primaryText of the selected <MenuItem/>. Can anyone provide guidance on how to achieve this? ...

Exploring the validation of arrays containing objects and sub-objects with Express Validator wildcards

I have been attempting to validate the data within an array of objects in a JSON request. Despite using express-validator wildcards as outlined in the documentation, I am receiving error messages regardless of whether the object properties are empty or not ...

I am attempting to expand an array of objects divided into two distinct inputs within a React component

There is an array of objects named estimate, with keys 'cost' and 'service'. By clicking 'Add', a new index (i) can be added to the array. The problem arises on the first cycle where {'cost': 2500, 'service&apos ...

JavaScript heap exhausted while running Docker container

Typically, I start my application by running npm run dev. The package.json file contains a script like the one below: "scripts": { "dev": "nodemon server.ts", } Everything is working fine in this setup. I have cr ...