In the following code what I want is to have an interface that enforces an argument to have the same type used in the function defined in that interface. So far it's easy, and I can use a generic type to achieve it:
interface Interface<T> {
arg: T
func: (_: T) => string
}
What I then want is to be a able to have an array of those interfaces that can have different types between them (while still ensuring to have the same type between the argument and the function inside one of the interfaces).
Here is a function that takes such an argument:
const mainFunc = <T>(
items: Array<Interface<T>>
) => {
items.forEach(({ func, arg }) => func(arg))
}
Once I call it, it works if all interfaces use the same type like so:
mainFunc([
{ arg: 'abc', func: _ => typeof _ }, // string typed Interface
{ arg: 'def', func: _ => typeof _ }, // string typed Interface
])
But fails if the interface uses different types like so:
mainFunc([
{ arg: 2, func: _ => typeof _ }, // number typed Interface
{ arg: 'abc', func: _ => typeof _ }, // string typed Interface
])
Telling me that type string
is incompatible with type number
.
I know that the type number
is infered by the fist line, and that it then breaks the second line.
Is there a way to have an array of interfaces using internally the same type while being typed differently between them?