2

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?

zedryas
  • 718
  • 6
  • 19
  • 2
    Possible duplicate of [Typescript array of different generic types](https://stackoverflow.com/questions/51815782/typescript-array-of-different-generic-types). I'm curious what both of you are doing that involves a value and a function to convert it to a string. – Matt McCutchen Aug 15 '18 at 14:08
  • thank you @MattMcCutchen i'm trying to wrap my head around your solution to see if it answer my question. The function in the example is just a dummy example, and the real use case it's quite different - in essence what i need is to ensure that the type of the arguments provided by the user of the function match the expected type as input of the function to prevent errors in execution. Since it's all typescript it should be able to computes it before execution. – zedryas Aug 15 '18 at 17:52

0 Answers0