Combining union types with intersection operators in Typescript

Here's a concept for an event handling system:

type EventMap = Record<string, any>;

type EventKey<T extends EventMap> = string & keyof T;
type EventReceiver<T> = (params: T) => void;

interface Emitter<T extends EventMap> {
  on<K extends EventKey<T>>
    (eventKey: K, fn: EventReceiver<T[K]>): void;
  emit<K extends EventKey<T>>
    (eventKey: K, params: T[K]): void;
}

// example usage
const eventHandler = eventEmitter<{
  data: Buffer | string;
  end: undefined;
}>();

// OK!
eventHandler.on('data', (x: string) => {});

// Error! 'string' is not assignable to 'number'
eventHandler.on('data', (x: number) => {});

The setup functions correctly but I have questions about it:

  1. Why is EventKey defined with string &?

  2. Do we really need generics K in the on and emit methods or could we simplify them by using just keyof T for the type of eventKey?

Thank you for your insights.

Answer №1

Why is it necessary to append a string & here?

The use of string & ... ensures that only keys of type string are valid for defining the EventKey type.

Despite EventMap being declared as Record<string,any>, it is still possible to assign an object with non-string properties:

const a: EventMap = {
  foo: 'bar',
  100: 'baz', // error, not a string property
}

Why does this happen? Because objects can have excess properties.

In such scenarios, string & keyof T would return never for properties that are not of type string.

Could eventKey parameter's type simply be keyof T?

This allows for keys defined as union types that extend string (Refer to this answer):

type EnumK = 'alpha' | 'beta'
type MyObject = {[P in EnumK]: string }

const obj: SomeObj = {
  alpha: 'foo',
  beta: 'bar'
}

In this case, the keys of obj represent an extension of string, specifically the union of string literal types alpha and beta. By using K extends ..., you capture this relationship and ensure type safety when indexing T[K].

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

The error message indicates that the 'aboutData' property is not found within the 'never[]' data type

What is the correct method for printing array elements without encountering the error message "Property 'post_title' does not exist on type 'never[]'?" How can interfaces be used to define variables and utilize them in code for both ab ...

Utilizing the functionalities provided by node.js, I came across an issue and sought out a solution for the error message "TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a function"

I have created a project centered around {typescript, react, electron, gaea-editor}. During an event, I utilized fs.writeFile() but encountered an error. The specific error message was: TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a functi ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

What are the steps to initiating a phone call using Nativescript?

When I click the button, I want to initiate a phone call dialing the number displayed on the label. Here is my custom button: <ActionBar> <NavigationButton (tap)="onBackTap()" android.systemIcon="ic_menu_back"></NavigationButton> ...

What causes interface to generate TS2345 error, while type does not?

In the code below: type FooType = { foo: string } function fooType(a: FooType & Partial<Record<string, string>>) { } function barType(a: FooType) { fooType(a) } interface FooInterface { foo: string } function fooInterface(a: FooInt ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Retrieve a static property from a specific type

I've encountered a dilemma with the code snippet below: class Action { public static DEPENDENCIES: (typeof Action)[] = []; public static MIN_USES: number | null = null; public static MAX_USES: number | null = null; } class SomeAction ext ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned to type 'string | string[]'

export class AuthService { constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { } login(email: string, password: string) { return this.webService.login(email, password).pipe( shareReplay(), ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Determining the data type of a property within an interface using TypeScript

Is there a way to extract the type from an interface based on its property name in order to use it in a Record? I am struggling with the syntax needed to retrieve the type by property name. My goal is to make this process more future-proof so that if the i ...

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Converting Enum Values into an Array

Is there a way to extract only the values of an enum and store them in an array? For example, if we have: enum A { dog = 1, cat = 2, ant = 3 } Desired output: ["dog", "cat", "ant"] achieved by: Object.values(A) Unfor ...

What are the steps to validate a form control in Angular 13?

My Angular 13 application has a reactive form set up as follows: I am trying to validate this form using the following approach: However, I encountered the following error messages: Additionally, it is important to note that within the component, there ...

React Native is throwing an error message saying that the Component cannot be used as a JSX component. It mentions that the Type '{}' is not assignable to type 'ReactNode'

Recently, I initiated a new project and encountered errors while working with various packages such as React Native Reanimated and React Navigation Stack. Below is my package.json configuration: { "name": "foodmatch", "version ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...