Adrian Pop
Adrian Pop

Reputation: 1967

Get the type of the value of a generic's property specified via another field

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:

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?

Upvotes: 4

Views: 1229

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

You just need another generic parameter to "connect" the key and value types of the interface:

type Device = {
    name: string;
    model: number;
}

interface Pair<T, K extends keyof T> {
    key: K,
    func: (value: T) => T[K]
}

Might as well remove the function parameter:

interface Pair<T, K extends keyof T> {
    func: (value: T) => T[K]
}
const pair: Pair<Device, 'model'> = {
    // key: 'model',
    func: (value) => ''
}

Upvotes: 2

Related Questions