How do EventEmitter<undefined> and EventEmitter<void> differ from each other?

At times, there may be a situation where we need to omit the generic variable. For example:

@Component( ... )
class MyComponent {

  @Output()
  public cancel = new EventEmitter<undefined>();

  private myFoo() {
    this.cancel.emit(); // no value needs to be passed
  }
}

Now, here comes the question: What is the better way to define the EventEmitter type?
EventEmitter<undefined> or EventEmitter<void>.

  • void is preferable because no argument is required in the .emit() method call.
  • undefined is better as .emit() functions similarly to .emit(undefined).

What are your thoughts on this matter?

Answer №1

As stated in the TypeScript documentation, the void type allows for both undefined and null values. This means that the provided code snippet would be considered valid:

@Component( ... )
class MyComponent {

  @Output()
  public cancel = new EventEmitter<void>();

  private myFoo() {
    this.cancel.emit();
    this.cancel.emit(undefined);
    this.cancel.emit(null);
  }
}

In contrast, if using EventEmitter<undefined>, you are limited to passing only undefined or no argument at all. While it may be more accurate in your specific case, there shouldn't be any major issues if you choose to pass null to an emitter where a value is not anticipated. Therefore, opting for void might be preferable due to its brevity.

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

Angular error validation for enforcing minimum and maximum lengths

this.employeeForm = this.fb.group({ fullName: [ '', [ Validators.required, Validators.minLength(2), Validators.maxLength(10), ], ], email: [''], skills: this. ...

Using Observable<any> as an input argument in a child component

When a button is clicked, a different Observable is loaded. In the main component, I have this : <button (click)="onClickMe1()">Click me 1!</button> <button (click)="onClickMe2()">Click me 2!</button> However, nothing appears in ...

Angular 10's tree shaking feature successfully eliminated the AsyncPipe module when setting sideEffects to false

Angular 10's tree shaking feature is causing unexpected issues with my AsyncPipe. A recent blog post on Angular 10's release notes introduces a new --strict mode for ng new: One interesting point it raises is: Setting up your app as side-effe ...

What is the best way to link the value of a mat-slider to an input field in a reactive form?

Is there a way to synchronize the min and max values of a ranged mat-slider with corresponding input fields? Currently, when I set numbers in the input fields, the slider updates correctly. However, when I use the slider to change the value of the input fi ...

Mastering the implementation of type refinements for io-ts in processing input data

I have implemented io-ts for defining my typescript types. This allows me to perform runtime type validation and generate type declarations from a single source. In this particular scenario, I aim to create an interface with a string member that needs to ...

Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code: import * as mathFn from './formula/math'; export functi ...

Dynamic translation using Angular 6's i18n functionality

I'm working on translating a piece of code using Angular's i18n. Everything seems to be in order, but I'm facing a challenge with translating the words 'Enable' or 'Disable' based on the dynamic status of the item. The se ...

Enhance a subject's behavior by overriding the .next method using a decorator

Currently, I am working on an Angular application where I have numerous Subjects, BehaviorSubjects, and ReplaySubjects as properties in various services. I am attempting to create a TypeScript decorator that can be added to some of these Subjects to enhanc ...

The return value depends on the type of function argument passed

I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects (). For example, when making a request like GET /article: { data: { type: 'article&ap ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

Why are nested RxJS map operators used and how do they impact data transformation?

Recently, I enrolled in an online Angular course and discovered that RxJS plays a significant role in web development. While exploring different concepts, I encountered a nested map operator that intrigued me. Although I can somewhat decipher what is happe ...

The 'localstorage' object is not defined in NextJS 14, make sure to use 'client' in server-side execution

While setting up the Tailwind context for a Next.js 14 website, I encountered an issue with configuring a global theme for my project. Despite creating the ThemeContext and adding 'use client' at the beginning of the file, it still caused an erro ...

Guide to configuring global providers in Angular2 version 2.0.0 RC.5

What is the process for setting up global providers when utilizing a new feature called NgModule? In previous instances, I could accomplish this with the following code: bootstrap(AppComponent, [ GlobalServiceAAA, GLOBAL_PROVIDERS_BBB ]); When usin ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...

Issue: The module '@nx/nx-linux-x64-gnu' is not found and cannot be located

I'm encountering issues when trying to run the build of my Angular project with NX in GitHub Actions CI. The process fails and displays errors like: npm ERR! code 1 npm ERR! path /runner/_work/myapp/node_modules/nx npm ERR! command failed npm ERR! c ...

Tips for utilizing angular pre-rendering alongside transloco?

After I prerender my Angular application, I am encountering an issue where the translation text is not visible when using Transloco. This is because it utilizes HTTP to fetch data from asset/i18n/en.json. Is there a way to implement prerendering with dyna ...

Navigating the diverse types of React HTML DOM events within a function concatenation

Question: Is it possible to merge different HTML DOM event types in Typescript? (I am aware of the option to split my function into two separate functions to avoid this error, but I would like to find another solution) Here is an example of my component ...

Transitioning from AngularJS to Angular 2: Exploring Alternatives to $rootScope.$on

Our journey with the AngularJS project has begun on the path towards the modern Angular. The ngMigration utility advised me to eliminate all dependencies on $rootScope since Angular does not have a concept similar to $rootScope. While this is straightforw ...

Is there a way to loop through a Http response object and extract Key Value pairs?

After receiving a response from an HTTP request, the code snippet below shows how to handle it: getEmployee(id: number){ this.empservice.getEmployee(id) .subscribe({ next:(res)=>{ this.obj = res; }, error:(err)=>{ ...

Angular displays X items in each row and column

I've been struggling with this task for the past 2 hours. My goal is to display a set of buttons on the screen, but I'm facing some challenges. The current layout of the buttons doesn't look quite right as they appear cluttered and unevenly ...