Using TypeScript's .map method to add a new property to an array of objects results in an error stating that the property does not

type Dog = { name: string; furColor: "brown" | "white" };

const addLocation = (animals: Dog[], location: "Italy" | "France") =>
    animals.map((animal) => (animal.location = location)); // animal.location throws error (see below)

throws

Property 'location' does not exist on type 'Dog'.ts(2339)

Is there a way to keep the Dog type as it is and to introduce a new type like LocationAddedDog in the addLocation function?

Answer №1

When using Array.map, the return value of the function passed is utilized to create the elements of a new array. In your scenario, it would look like this:

type Cat = { name: string; fur: "brown" | "white" };

const addOrigin = (animals: Cat[], origin: "Italy" | "France") =>
    animals.map((animal) => ({ ...animal, origin }));
    

The return type of addOrigin will now contain the origin property.

You can rely on type inference for the rest, but if you wish to define OriginAddedCat, you have a few options:

interface Cat {
    name: string;
    fur: "brown" | "white";
}

interface OriginAddedCat extends Cat {
   origin: "Italy" | "France";
}

or

type OriginAddedCat = Cat & { origin: "Italy" | "France" };

or

type OriginAddedCat = ReturnType<typeof addOrigin>[number];

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

Oh no! A critical mistake has occurred: Mark-compact operations are not working efficiently near the heap limit, leading to a failed allocation due to the

My project is not particularly complex, I only just started it. However, when I run the command npm run dev, node js consumes more than 4GB of memory and eventually crashes with a fatal error: --- Last few GCs --- [16804:0000018EB02350F0] 128835 ms: Mar ...

A practical guide to troubleshooting typescript errors when exporting a map component

I encountered a typescript error when trying to export the map component with GoogleApiWrapper. It works fine when not wrapped in GoogleApiWrapper, but all my attempts to resolve the issue have failed. I would appreciate it if someone could review the code ...

Simultaneously iterate through two recursive arrays (each containing another array) using JavaScript

I have two sets of arrays composed of objects, each of which may contain another set of arrays. How can I efficiently iterate through both arrays and compare them? interface items { name:string; subItems:items[]; value:string; } Array A=['parent1&ap ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

How to generate an array within a TypeScript extension function

As I was working on creating an extension method using typeScript, the main goal was to establish a static or normal variable within the method. The ServiceCollector method was invoked three times in order to send and store data or objects in an array. B ...

Tips for verifying the results of a specific element on a webpage using Angular

Hello all, I am currently learning Angular and facing an issue related to components. I have successfully created a component named "test". When I execute the code, I get the desired output. However, if I remove the tag from app.component.html, I end up ...

Overtaking a property in a node_module interface: a guide

I am facing a situation where I need to modify an existing interface property in my custom type declaration file, rather than creating a new one. Despite trying various approaches, such as attempting to omit the property, I have not been successful in ach ...

I'm having trouble with TypeScript locating a method specified in a parent class's type definition. What might be causing this issue?

While working with JointJS, I came across the defined typings. In my Typescript class, the structure is as follows: namespace joint { namespace shapes { namespace devs { class Model extends basic.Generic { ... } } } } ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

Navigating the world of NestJs and TypeScript with the `mongoose-delete` plugin: a comprehensive guide

I am currently utilizing Mongoose within the NestJs library and I want to incorporate the mongoose-delete plugin into all of my schemas. However, I am unsure of how to implement it with nestJS and Typescript. After installing both the mongoose-delete and ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

Anticipating the outcome of various observables within a loop

I'm facing a problem that I can't seem to solve because my knowledge of RxJs is limited. I've set up a file input for users to select an XLSX file (a spreadsheet) in order to import data into the database. Once the user confirms the file, v ...

Issue with Angular 11: Unable to bind to 'ngForOf' as it is not recognized as a valid property of 'tr' element

My issue lies with a particular page that is not functioning correctly, even though it uses the same service as another working page. The error seems to occur before the array is populated. Why is this happening? I appreciate any help in resolving this p ...

Tips for utilizing the JS attribute "offsetWidth" within Angular 4

I am attempting to retrieve the width of an element using JavaScript in my Angular application. document.getElementsByClassName("element")[0].offsetWidth; However, I keep encountering the following compilation error: Property 'offsetWidth' d ...

How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet: class A { x = 0; y = 0; visible = false; render() { return 1; } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; type JustMethodKe ...

The type 'contextPaneTitleText' argument cannot be assigned to the parameter type 'key of RemoteConfig'

I am encountering an issue when using the following code snippet: const contextPaneTitleText = useFeature("contextPaneTitleText").asString(); This code is resulting in an error message: Argument of type '"contextPaneTitleText" ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

What is the most efficient method for incorporating React into Wordpress while using Typescript?

Is it possible for me to utilize the React / React-Dom scripts that Wordpress has enqueued in my bundled javascript, while still being able to use the -dev installed React for development purposes? The javascript files are designed for a WordPress plugin ...

Property ngIf in Angular is not being supplied by any relevant directive within the embedded template

When attempting to use ngIf, I encountered an error with a red underline. The error message states: "Property ngIf is not provided by any applicable directive on an embedded template." I then attempted to import commonModel, but received a new error: "src ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...