Is it possible work with array's elements with different union types without "is not assignable to parameter of type 'never'" error?

Viewed 79
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)
*/

Example on TS playground

Is it possible to implement it without this issue, or how to lead proposed structure to be abble to hanlde it set(state) in common way without boilerplates like perform this operation for each child manually or overcodes like [() => set1(state1), () => setN(stateN)]?

1 Answers

After of continious invastigation I found the way which can work for me.

Link to TS playground to play.

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 to investigate to finally understanding. If anybody could review the proposal with feedback I will be very appreciate.

Related