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)]?
Array<Foo<string>|Foo<number>>, one would end up withArray<FooExistentiallyQuantified>. Does it actually work if one hasFoo<string>|Foo<number>? It seems that it cannot useexistentialize-like nat trafo inside of themap, so one is forced to castFoo<string>|Foo<number>to something likeFoo<any>, and at that point the whole previous construction seems to become unnecessary. Are there better solutions?Array<Foo<string>|Foo<number>>. I think we basically need a way to say that, since the same function typechecks on both branches, it should typecheck on the union. Right now the compiler is destroying the "correlation" betweensetandstate. Close vote retraced.