Can we manipulate array elements with various union types without encountering the error "is not assignable to parameter of type 'never'?"

type GenericElement<T> = {
  set: Setter<T>;
  state: T;
} 

type Setter<T> = (state: T) => void

type GenericElements = Array< GenericElement<string> |  GenericElement<number>>

const genericElements = [{
  set: (state: string) => console.log(state),
  state: 'stateValue'
}, {
  set: (state: number) => console.log(state),
  state: 123
}]

genericElements.map(({set, state}) => set(state))
// ---------------------------------------|

/**
 * Argument of type 'string | number' is not assignable to parameter of type 'never'.
 * Type 'string' is not assignable to type 'never'.(2345)
*/

View the example on TS playground

Can this issue be resolved or is there another approach to handle the set(state) operation without manual intervention for each child element or excessive code like

[() => set1(state1), () => setN(stateN)]
?

Answer №1

Upon thorough investigation, I have discovered a solution that works best for me.

Click on TS playground to start playing.

enum genericTypes {
    stringTypes = 'stringTypes',
    numberTypes = 'numberTypes',
}
const {numberTypes, stringTypes} = genericTypes;

type GenericElement<T extends genericTypes> = {
    set: Setter<T>;
    state: State<T>;
};

type State<T extends genericTypes> = T extends genericTypes.numberTypes ? number : string;

type States = {
    [numberTypes]: State<genericTypes.numberTypes>;
    [stringTypes]: State<genericTypes.stringTypes>;
};

type Setter<T extends genericTypes> = (state: State<T>) => void;

type Setters = {
    [numberTypes]: Setter<genericTypes.numberTypes>;
    [stringTypes]: Setter<genericTypes.stringTypes>;
};

const setters: Setters = {
    [numberTypes]: (state: State<genericTypes.numberTypes>) => console.log(state),
    [stringTypes]: (state: State<genericTypes.stringTypes>) => console.log(state),
};

const states: States = {
    [numberTypes]: 123,
    [stringTypes]: '123',
};

type GenericElements = Array<GenericElement<genericTypes>>;

const genericElements: GenericElements = [
    { set: setters.numberTypes, state: states.numberTypes },
    { set: setters.stringTypes, state: states.stringTypes },
];

genericElements.map(({ set, state }) => set(state));

I will continue my research until I fully grasp the concept. Any feedback on the proposal would be greatly appreciated.

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

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

Passing data from a container component to a Redux Form component in React with TypeScript

One of my Form container components looks like this: class PersonalDetailContainer extends React.Component<PropTypes> { onSubmit = async (fields: PersonalFields) => { this.props.savePersonalDetail(fields); }; render(): JSX.Element { ...

Angularfire2 retrieve list of data with a specified number of items from the

I am facing a challenge in retrieving a specific node from my firebase database. https://i.sstatic.net/YDevB.png The technologies I am using include: "angularfire2": "^5.0.0-rc.4", "firebase": "^4.9.0", In my component code, you can find the following ...

Uncomplicating RxJs Operators: Decoding switchMap and combineLatest

I currently have the following RxJS subscription : combineLatest([obs1$, obs2$]) .pipe( filter(val=>!!val[0] && !!val[1]), // ensuring no null values on both observables switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$( ...

Determining the property type in Typescript based on the value of another property

Unique Code interface Order { customer: Customer, address: Address } interface Customer { name: string } interface Address { firstLine: string } interface OrderUpdateRequest { key: 'customer'|'address', value: ...

Transition from using ReactDOM.render in favor of asynchronous callback to utilize createRoot()

Is there a React 18 equivalent of this code available? How does it handle the asynchronous part? ReactDOM.render(chart, container, async () => { //code that styles some chart cells and adds cells to a worksheet via exceljs }) ...

Customizing key values within nested objects in Angular2: A comprehensive guide

I need assistance with setting up a JSON object for a post in Angular2/Typescript. I am trying to dynamically set the nested object values for a key. Is it possible to achieve this using Angular2/Typescript? I have attempted to retrieve the values from JS ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Accessing services from the main page's popover callback in Ionic 2 is essential for enhancing user interaction and

After spending some time working with angularJs, I recently made the switch to angular 2. I am facing an issue with calling a popover from a page and fetching data from an API when an item is selected from the popover. The problem arises when I try to acce ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

When attempting to send a fetch request in the most recent rendition of NextJS, it ends up with an error of 'failed fetch'

I am currently working on a nextjs (v.13.4.19) / strapi (v.4.12.5) application and facing issues when trying to make a request to the strapi endpoint using the fetch function. I have attempted several troubleshooting steps such as: changing localhost:1337 ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

Is it possible to target a specific element using Angular2's HostListener feature? Can we target elements based on their class name?"

Is there a way in Angular2 to target a specific element within the HostListener decorator? @HostListener('dragstart', ['$event']) onDragStart(ev:Event) { console.log(ev); } @HostListener('document: dragstart' ...

What is the C sharp version of this code structure?

I'm curious to know what the C# syntax is for declaring a property like this: filters: { [arg: string]: string }; ...

"Refining MongoDB queries with a filter after performing a populate

I want to retrieve all records with populated attributes in a query. Here is the TypeScript code: router.get("/slice", async (req, res) => { if (req.query.first && req.query.rowcount) { const first: number = parseInt(req.qu ...

Transform coordinated universal time to the corresponding local time using Angular

Looking to transform the UTC format date into an India date and time format using Angular 2019-02-18T17:31:19-05:00 I am looking for it to be in the following format: DD/MM/YYYY HH:MM(eg: 02/19/2019 04:01 AM). Any guidance on how to accomplish this would ...

Arrange items by their keys while keeping their current values in order to correspond to the array sequence

I have two sets of data. First one is in the form of (footerMenuOptions): [{Home: true}, {About: false}, {Features: false}, {Contact: false}]  The second set is in the form of (this.navbarMenuOptions): ["Home", "About", "Features", "Contact"] Occasio ...

Tips on integrating ActiveX controls in Angular

I built my project using Angular 6 and TypeScript in Visual Studio Code. The browser being used is IE11. Unfortunately, when I try to run the code written in app.component.html, it doesn't work as expected. The HTML code causing the issue is: <d ...

Typescript mistakenly infers the wrong type: TS2339 error - it says that property 'selected' is not found on type 'string'

When examining the code snippet below, Typescript initially infers a type string for the inner element type of the values array. However, it subsequently raises an error indicating that string does not have the property "selected". let item = { values: [{ ...