Better event type in Angular event handlers

I was learning Angular and Udemy video course as well as the official docs show this code:

export class KeyUpComponent_v1 {
  values = '';


  onKey(event: KeyboardEvent) { // with type info
    this.values += (<HTMLInputElement>event.target).value + ' | ';
  }
}

this looks much better in ReactJS with typescript, where event target have proper type:

onClick(event: MouseEvent<HTMLButtonEvent>) {

}

But this don’t work in Angular, you got Error: “Type ‘MouseEvent’ is not generic.”

So I’ve thought that I should try to create this type for Angular. And it look like this:

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

interface GenericEvent<T> extends Omit<Event, 'target'> {
    target: T;
}

You can use this type like this:

@Component({
    selector: 'app-input',
    template: '<input (input)="onInput($event)"/>'
})
export class InputComponent {
    value = '';
    onInput(event: GenericEvent<HTMLInputElement>) {
        this.value = event.target.value;
    }
}

NOTE: in this example I’ve used Event interface as base for GenericEvent, but for input event there is more specific type which is InputEvent.

And you can easily create event for each Event type in TypeScript (here are the list of Events interfaces, I’m not sure, but probably they all are types (interfaces) in TypeScript).

If you would like single type with two values, check this Stack Overflow post: Generic interface extending parameterized interface in TypeScript.

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: