Apply a spread of nested elements onto another spread

I am working with an array containing last names of Persons and need to populate new entries. However, I only have the last names and not the full Person objects. How can I address this issue?

type Person = {
   name: string,
   lastName: string,
   age: number
}

function MyComponent() {
   const [persons, setPersons] = useState<Person[]>([])

   function addNewPersons(lastName: string[]): void {
      setPersons((prevState: Person[]) => [
         ...prevState,
         // spread lastName[] onto Person[]
      ]);
   }

   return <></>;
}

Answer №1

Here's a potential solution...

interface User {
  username: string;
  email?: string;
}

function UserProfile() {
  const [users, setUsers] = useState<User[]>([]);

  function addNewUsers(usernames: string[]) {
    const newUsers: User[] = usernames.map((username) => ({
      username,
    }));
    setUsers((prevUsers: User[]) => [...prevUsers, ...newUsers]);
  }

  return <></>;
}

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

Implementing Typescript with React: Assigning event.target.name to state

I am facing an issue with a React state that has specific named keys defined in an interface... Despite trying a potential solution based on the state keys, I am still encountering an error... { [x: string]: string; }' provides no match for the sign ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

Mongodb Dynamic Variable Matching

I am facing an issue with passing a dynamic BSON variable to match in MongoDB. Here is my attempted solutions: var query = "\"info.name\": \"ABC\""; and var query = { info: { name: "ABC" } } However, neither of thes ...

Creating a Typescript union array that utilizes a string enum for defining key names

Can we shorten this statement using string enum to restrict keys: Array<{ [enum.example1]: Example } | { [enum.example2]: Example } | ...> // or equivalent ({ [enum.example1]: Example } | { [enum.example2]: Example } | ...)[]; We can make it more c ...

What is the specific type of event for a change handler in TypeScript?

As a newcomer to TypeScript, I recently crafted a change handling function that accepts the event as a parameter to assign the value, like event.target.value. Currently, I have designated this as any, but I suspect there is a more appropriate type for this ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Creating a comprehensive object within a single interface using Typescript

Here is an example of an Object in TypeScript: export class test{ recordname: string; comments: [{ comment: string }] } To define it using one interface instead of multiple interfaces, you can try something like this: export int ...

Prevent TypeScript from allowing strings or arrays to be assigned to types with no properties

Can we limit the input for param so that it does not allow strings, arrays, etc.? interface bar { x?: number; y?: string; } function qux(param: bar) { } qux("hello"); ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Troubles with input handling in Angular

I've been diving into Traversy Media's Angular crash course recently. However, I've hit a roadblock that I just can't seem to get past. The problem arises when trying to style the button using a specific method. Every time I save and pa ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...