Union of functions in TypeScript causes arguments to be transformed to "never"

I am working with multiple interfaces, each containing a property called `type`.

interface Type1 { type: 'key1', name: string }
interface Type2 { type: 'key2', description: string, name: string }
interface Type3 { type: 'key3', cost: number }

In addition to the interfaces, I have a mapping interface:

interface TypeMap {
   key1: Type1,
   key2: Type2,
   key3: Type3
}

There is also a union type:

type TypeElement = Type1 | Type2 | Type3

I have created a map object that uses records of each type separately, similar to the mapping interface:

const allTypes: { [key in keyof TypeMap]: (record: TypeMap[key]) => void } = {
   key1: (record) => {},
   key2: (record) => {},
   key3: (record) => {},
}

However, when passing a variable of type `TypeElement` into a callback from `allTypes`, an error occurs:

const func = (record: TypeElement) => {
   const cb = allTypes[record.type]
   return cb(record)
}

The error message states:

Argument of type 'TypeElement' is not assignable to parameter of type 'never'. The intersection 'Type1 & Type2 & Type3' was reduced to 'never' because property 'type' has conflicting types in some constituents. Type 'Type1' is not assignable to type 'never'.

Why does this error occur? What is the issue here? How can I pass a record to `cb` without encountering this error? Using `record as never` or `as any` is not the solution I am seeking!

Answer №1

Here is a set of interfaces and types in TypeScript:
- Type1: { type: 'key1', name: string }
- Type2: { type: 'key2', description: string, name: string }
- Type3: { type: 'key3', cost: number }

We also have a TypeMap interface that maps keys to the corresponding types:
{
   key1: Type1,
   key2: Type2,
   key3: Type3
}

A TypeElement can be either Type1, Type2, or Type3.

In the allTypes object, we define functions for each type in TypeMap:
{
   key1: (record) => {},
   key2: (record) => {},
   key3: (record) => {},
}

The func function takes a record of type K from TypeMap and calls the corresponding function from allTypes based on the record's type.

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

How can I link an object to a variable using a select tag in Aurelia with Typescript?

After successfully populating a select tag with options from a static array of objects in JSON, each option set to the object id, I encountered a new challenge. tvs: any[] = [ { "id": 1, "ip": "11.11.11.111", "port": "8080", "name": "tv 1" }, ...

Retrieve the item from the array that has the property set to true using React and TypeScript

I am still learning about TypeScript. I have an array of objects with different properties, let items = [{ "Id": "1", "Test": true }, { "Id": "2", "Test": true }, { "Id": "1", "Test": true, "ShowAttribute": true }]; // Here, I am attempti ...

Angular 10: Manually include the (*)d.ts file in the compilation process

I am currently experiencing an issue with my Angular library that has description files *.d.ts in a specific structure as shown below: ├ src │ ├ my-lib │ │ ├ my-typedef.d.ts │ └ public_api.ts │ └ tsconfig.lib.json In the tsconfi ...

Looping over object properties using ngFor in an Angular applicationI have a question about looping

Instead of using keyValuePipe or {{data | JSON}}, I am looking for a different solution to write my data. How can I achieve this by using Object.entries, Object.keys, or Object.values? Check out the code with JSON in Stackblitz here: https://stackblitz.co ...

Transforming a React component into a TypeScript Element results in an automatic 'any' type assignment due to the inability to index an expression of type 'string | number'

I am currently in the process of migrating a React component to TypeScript, but I have encountered an issue that I am struggling to resolve. I am consistently receiving an error related to accessing variantStyles[variant][color], and I cannot pinpoint the ...

The debugger extension for Visual Studio Code in Chrome, [webkit-debug-adapter], received a response from the target application, but was unable to find any valid target

I am currently working on an Angular/TypeScript application and have been able to debug the TypeScript code in Chrome thanks to the map files. Recently, I decided to install the Debugger for Chrome extension from Visual Studio Marketplace. You can find it ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

ReactJS does not support merging multiple pages into one based on user button selection

My goal is to dynamically load a component based on the user's current page. List of Pages: Executables Shop In the main screen, there is a sidebar with two icons. The primary button should set the Executables Page and the second button should set ...

While performing compilation, Angular's ngFor triggers an error when used with SVG elements

I am attempting to create a recursive function of lines in order to generate a graph, but I am encountering a strange error in the console. It works fine on node.js. Below is the code snippet: <svg height = "200" width = "300"> ...

"Using Jest's mock to expect a different set of arguments passed with toHave

Currently, I am experimenting with the functionality within TripService: async createAndMapTrips<T extends ITripEntity>( driver: DriverEntity, entities: T[], intervalInMinutes: number = 10, ): Promise<[TripEntity[], T[ ...

Getting dynamic JSON data using TypeScript's generic types

I need to retrieve generic JSON data from the backend, with a variable number of values and keys. How should I modify my get method to handle this? Currently, my code looks like this: getArticoliByDesc = (descrizione : string) => { return this.httpC ...

What is the best way to confirm that a certain element is not present on the page using playwright?

My current challenge involves testing a website that features a logo, and I need to ensure that the logo does not display on specific pages. I have been exploring the Playwright assertions documentation for guidance on how to assert that an element does N ...

Is it possible to utilize the Lit javascript module from a CDN without including the bundled Lit dependencies?

Is there a method to distribute a Lit element created from TypeScript without including the Lit dependencies in the web component bundle? For instance, we can serve the rollup bundle as mentioned here from Unpkg. However, I am curious if it's possibl ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

Using debounceTime and distinctUntilChanged in Angular 6 for efficient data handling

I recently came across a tutorial on RxJS that demonstrated the use of debounce and distinctUntilChanged. I'm trying to implement it in Angular 6, but I'm facing some challenges. Here is the code from the tutorial: var observable = Rx.Observabl ...

Using Typescript, you can specify an array of type <T> within an object

Having a background in JS, I am currently exploring TS. My goal is to create an object with a single field, which is an array of strings, while ensuring strong typing. let container = { items: ['Item 1'] } container.items[0] = 3; // This is i ...

Troubleshooting Angular's HTTP Get Functionality

Currently, I am developing an application where the client is built using Angular and the server is in C. I am facing an issue with my HTTP Get method but unable to pinpoint the problem. The function "updateStream()" is invoked every 70 milliseconds. publ ...

A declaration file for the module 'module-name' was not found. The file '/path/to/module-name.js' is assumed to have a type of 'any' by default

After diving into the inner workings of TypeScript module resolution, I stumbled upon an issue. Within my repository @ts-stack/di, the directory structure post-compilation looks like this: ├── dist │   ├── annotations.d.ts │   ├─ ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

With a GroupAvatar, my Avatar named "max" likes to dance to the beat of its own drum rather than following the rules of my

I am currently working on creating an AvatarGroup using MaterialUi. I have successfully applied a style to all my avatars, except for the avatar that is automatically generated by AvatarGroup when the "max" parameter is defined. const styles = makeStyl ...