Let's say I have the following type:
type Device = {
name: string;
model: string;
}
type Service {
name: string;
device: Device;
}
Let's say I want a generic object Pair having a key and a func property. The key should be an existing field on the given generic type T and func (optional parameter) should be a function that receives a single parameter being the value received by indexing T with key. How do you actually type func properly?
interface Pair<T> {
key: keyof T;
func?: (value: ?) => ?
}
I tried having something like func: (value: T[key]) => typeof T[key]
but I'm not sure what's the right approach.
Expected behaviour:
- if I do
p: Pair<Device> = { key: "name", func: (value) => ...}
, value should be inferred as being a string - if I do
p: Pair<Service> = { key: "device", func: (value) => ...}
, value should be inferred as being a device
Extra:
What if I want to have a function that receives an array of these kind of pairs? How would the type of that parameter look like?