'How to match argument array type with return array?

I have this array:

[
  { name: "Tree", value: 1 },
  { name: "Ball", value: 'b' },
  { name: "House", value: ['this', 'is', 'a', 'test'] }
]

And I want to return a different array where the field value of the above objects is part of the type. Like this:

type Names = "Tree" | "Ball" | "House"

type Input<K extends Names> = Array<{ name: K, value: any }>

type FuncValue<T> = T extends Array<{ value: infer Value }> ? Value : never;

function test<K extends Names, I extends Input<K>> (input: I): FuncValue<I> {
  return input.map(i => {
    return i.value
  })
}

test([
  { name: "Tree", value: 1 },
  { name: "Ball", value: 'b' }
]) // Returns [1, 'b'] and the type should be [number, string]

The above code does not work, but it is as close as I can get.


The return type bust be an array of types based on the input (not a union of types)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source