Breaking down an object using rest syntax and type annotations

The interpreter mentions that the humanProps is expected to be of type {humanProps: IHumanProps}.

How can I properly set the type for the spread operation so that humanPros has the correct type IHumanProps?

Here's an example:

interface IName {
  name: string
}

interface IHumanProps {
  hobby: string,
  age: number
}

interface IHuman extends IName, IHumanProps {}

const human: IHuman = {
  name: 'Linda',
  hobby: 'reading',
  age: 99
}

const { name, ...humanProps }: { name: string, humanProps: IHumanProps } = human;

console.log(name);
console.log(humanProps);

How can I destructure an object using the spread operator and specify types? I couldn't find much information on this particular scenario online.

[Edit]: I encountered an error where VSCode (or possibly the linter) was indicating that the deconstructed humanProps did not match the expected type IHumanProps, instead suggesting a type of

{humanProps: {humanProps: IHumanProps}}
, which was incorrect. This might have been an issue with VSCode/ESLint. Thank you all for the quick responses!

Answer №1

To improve clarity, I recommend revising the data types in the following way:


type PersonName = {
  firstName: string;
}

type PersonDetails = {
  interest: string;
  years: number;
}

type Person = PersonName & PersonDetails;

const person: Person = {
  firstName: 'Linda',
  interest: 'reading',
  years: 99
}

Now, to destructure the person object, you can simply use the code below:

const {firstName, ...personInfo} = 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

How can we retrieve the target element for an 'onSelectionChange' DOM event in Angular 6?

When using Angular 6, I want to retrieve the "formControlName" of the corresponding element whenever the selection changes. HTML <mat-form-field *ngIf="dispatchAdviceChildForAdd._isEditMode" class="mat-form-field-fluid"> <mat-select ...

How can a custom event bus from a separate account be incorporated into an event rule located in a different account within the CDK framework?

In account A, I have set up an event rule. In account B, I have a custom event bus that needs to act as the target for the event rule in account A. I found a helpful guide on Stack Overflow, but it was specific to CloudFormation. I am providing another a ...

Showing Information without NgFor Directives

I have successfully displayed data without using a ngFor loop. However, it is currently showing all the quote information from multiple customers. The CSS is arranged in such a way that the discount div is positioned next to the customerinfo div. Below is ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Tips for building an effective delete function in Angular for eliminating a single record from a table

I've been working on creating a method to delete an employee by their ID, and I've tried various approaches in my VS Code. Unfortunately, all of them have resulted in errors except for this specific method. Whenever I click on the delete button, ...

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

Tips for Ensuring the Observable Completes Before Subscribing

I utilized RXJS operators in my code to retrieve an array of locations. Here is the code snippet: return O$ = this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: fal ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

Step-by-step guide on incorporating HTML into a popover within Angular4

After successfully implementing a hover popover in Angular using PopoverModule from ngx-popover, I now need to modify the content inside the popover. My search led me to this example: <ng-template #popContent>Hello, <b& ...

What could be causing the error in Angular 2 when using multiple conditions with ng-if?

My aim is to validate if the length of events is 0 and the length of the term is greater than 2 using the code below: <li class="more-result" *ngIf="events?.length == 0 && term.value.length > 2"> <span class="tab-content- ...

The type 'typeof globalThis' does not have an index signature, therefore the element is implicitly of type 'any'. Error code: ts(7017) in TypeScript

I'm encountering an issue with my input handleChange function. Specifically, I am receiving the following error message: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017) when att ...

Is it possible for TypeScript to preserve the return type while consolidating multiple classes or objects of functions in a reducer method?

Describing my issue with the title was challenging, but here it is: I have several objects that follow this structure: type TUtilityFunction = {[key: string]: <T>(a: T, b: any) => T} For example: class UtilityA{ DoSomeWork = function (arg1: So ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: I have attempted to fix this issu ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...

Is it possible to create an Angular 2 service instance without relying on the constructor method?

I'm struggling to utilize my ApiService class, which handles API requests, in another class. Unfortunately, I am encountering a roadblock as the constructor for ApiService requires an HttpClient parameter. This means I can't simply create a new i ...

A TypeScript function that returns a boolean value is executed as a void function

It seems that in the given example, even if a function is defined to return void, a function returning a boolean still passes through the type check. Is this a bug or is there a legitimate reason for this behavior? Are there any workarounds available? type ...

What impact does introducing a constraint to a generic type have on the inference process?

Let's take a look at this scenario: function identity<T>(arr: T[]) { return arr } identity(["a", "b"]) In the above code snippet, the generic type T is inferred as string, which seems logical. However, when we introduce a ...

My goal is to develop a secure login system with authentication on the Angular platform

login(data: any) { this.user.getUsers().subscribe( (users) => { const user = users.find((u) => u.username === data.username && u.userpassword === data.password); if (user) { // Valid username and password, ...