Unpacking intricate function arguments in TypeScript

I am working with the following model classes:

export class Book {
    public name: string;
    public id: string;
    ...
} 

export class Author {
    public firstName: string;
    public lastName: string;
    ...
} 

The my-component triggers an event that utilizes objects of the aforementioned classes

this.archiveEntry.emit({ book: this.book, author: this.author });

The parent component in its HTML file includes my-component as shown below

<my-component (archiveEntry)="archiveEntryHandler($event)" ...> ...

and attaches the following handler to this event

public archiveEntryHandler({book: Book, author: Author}) {
  let line = `"${book.name}",  ${author.lastName}`;
  ...
}

however, I encounter the following compilation errors

error TS2552: Cannot find name 'book'. Did you mean 'Book'?

error TS2552: Cannot find name 'author'. Did you mean 'Author'?

How can I properly destructure the event parameter/s in the handler?

Answer №1

When writing the handler function,

archiveEntryHandler({book: Book, author: Author})

You assigned aliases to the book and author variables.

{ book: aliasForBook, author: aliasForAuthor }

To specify types for destructured variables, use this syntax:

archiveEntryHandler({book, author}: {book: Book, author: Author})

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

Error in TypeScript: Circular reference in type alias 'Argument' in node_modules/classnames/index.d.ts at line 13:13

Need help troubleshooting an error while building my project. Can't find much information online to resolve this issue. I am using typescript 4.2.4 I can't locate the classnames/index.d.ts file in any directory, so I'm unable to make any ch ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using setTimeout( #action#, timeMillis) with #action# as a lambda 2) supplying the lambda with a parameter. The common method of setTimeout( ()=>{ #callback# }, timeMillis) works flawlessly when extracting () ...

The FullCalendarModule does not have a property named 'registerPlugins' in its type definition

Currently in the process of integrating fullcalendar into my Angular 15 project and encountering the following error: Error: src/app/views/pages/takvim/takvim.module.ts:18:20 - error TS2339: Property 'registerPlugins' does not exist on type &apo ...

What is the best way to instruct Angular to exclude certain sections of a template from compilation?

My scenario is quite straightforward: I am looking to create documentation for my library by including code examples along with demo sections. My main query is this: How can I make one part of the code compilable and executable, while leaving the other pa ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

Unable to establish a connection between Laravel websocket and Angular

The CORS policy has blocked access to XMLHttpRequest from the origin 'http://localhost:4200' to the resource at 'http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MgBuvgw' because there is no 'Access-Control-Allow- ...

Utilizing ExpressJS in a NodeJS application with ES6 and Typescript

After confirming my information, I discovered that in an ES6 application, it is necessary to import dependencies using import .. from '..' instead of var .. = require('..'). I made the necessary changes to the imports, but encountered ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Exploring Angular unit testing for immutable variables

Currently, I am working on writing unit tests for a specific class that contains readonly class variables. I am trying to ensure complete test coverage and understand how to cover the logic inside these variables. import { Injectable } from '@angu ...

The pipe in Angular 2.0.0 was not able to be located

Error: Issue: Template parse errors: The 'datefromiso' pipe is not recognized Custom Pipe: import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'datefromiso' }) export class DateFromISO implements P ...

Encountering errors in Typescript build due to issues in the node_modules directory

While running a typescript build, I encountered errors in the node_modules folder. Despite having it listed in the exclude section of my tsconfig.json file, the errors persist. What's puzzling is that another project with identical gulpfile.js, tsconf ...

Encountered an error while attempting to install the DataTables npm package in an Angular

I am trying to add datatables to my angular application. Upon running ng add angular-datatables An error code is displayed (refer to the image). error image The cause of this error is unknown to me. Please review the package.json file as well. package.j ...

Guide on stubbing Google gapi global variable in component tests with Karma

I am currently facing a challenge in setting up tests for a service in my Angular 4 project that utilizes Google gapi. The issue arises from the fact that the variable is globally declared but not mocked, leading to an error when running the tests: Refe ...

Sending parameters with a linked Get request leads to a 404 error page

Exploring how to interact with an external API using a TS/Express server. The user will choose a product, triggering a GET request to the server, which then queries the external API for pricing data. This is a project for fun and learning purposes, so ple ...

Executing event sending from child to parent via ngx-translate

I have been working on creating a multilingual website in Angular using ngx-translate. I store language translations in JSON files located at assets/i18n/en.json (for English) and assets/i18n/ge.json (for German). To handle communication from child to pare ...

Entering key-value pairs into a dictionary to show correlation

I've been struggling to find a solution for what seems like a simple issue. The problem lies in typing a dictionary with values of different types so that TypeScript can infer the type based on the key. Here is the scenario: type Id = string; inter ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

What is the method for enabling imports from .ts files without file extensions?

While trying to open a Svelte project with TypeScript, I encountered an issue where all imports from .ts files were showing "Cannot resolve symbol" errors. https://i.stack.imgur.com/FCVxX.png The errors disappear when the .ts extension is added to the im ...

Attempting to start an Angular project using NG NEW constantly fails nowadays - always ends with error code EPERM

Can Angular still be considered a reliable framework when pervasive errors and bugs persist for extended periods without any clear resolution documented? .... 24695 silly saveTree | +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...