How can I listen for keypress event on the whole page?

I would use @HostListener decorator within your component: import { HostListener } from ‘@angular/core’; @Component({ … }) export class AppComponent { @HostListener(‘document:keypress’, [‘$event’]) handleKeyboardEvent(event: KeyboardEvent) { this.key = event.key; } } There are also other options like: host property within @Component decorator Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03 @Component({ … host: { … Read more

Typescript Interface – Possible to make “one or the other” properties required?

If you’re truly after “one property or the other” and not both you can use never in the extending type: interface MessageBasics { timestamp?: number; /* more general properties here */ } interface MessageWithText extends MessageBasics { text: string; attachment?: never; } interface MessageWithAttachment extends MessageBasics { text?: never; attachment: string; } type Message = … Read more

TypeScript union of string and string literals

This is currently considered a design limitation (see microsoft/TypeScript#29729) and/or a missing feature (see microsoft/TypeScript#33471) of TypeScript. From the type system’s point of view, string is a supertype of any string literal like “blue” or “red”, and so a union string | “blue” | “red” is the same as string and the compiler aggressively reduces … Read more

Typescript: How can I make entries in an ES6 Map based on an object key/value type

Here’s the closest I can imagine getting, although I still don’t understand why we don’t just use plain objects to begin with: type ObjectToEntries<O extends object> = { [K in keyof O]: [K, O[K]] }[keyof O] interface ObjectMap<O extends object> { forEach(callbackfn: <K extends keyof O>( value: O[K], key: K, map: ObjectMap<O> ) => void, … Read more