HarmonicTons
HarmonicTons

Reputation: 44

Infer type of value of corresponding key

Let's consider the following generic:

type KV<T, K extends keyof T> = {
  key: K; // any key of T
  value: T[K]; // corresponding value type of the key
}

KV<MyType, "myKey"> represents a {key: "myKey", value: ...} object based on MyType.

We can use it like this:

// random type
type MyType = {
  a: number;
  b: string;
}

// below, how could we infer K from the 'key: "a"' instead of setting it manually?
const kv : KV<MyType, "a"> = {
  key: "a",
  value: 47
}

kv is a valid object, but we have to specify the key twice. How could we update KV to infer the key automatically?

Thanks in advance!

Playground: https://www.typescriptlang.org/play?ssl=16&ssc=2&pln=1&pc=1#code/C4TwDgpgBA0gagHgCoBpZQgD2BAdgEwGcoBrCEAewDMokA+KAXigG8AoKU8gLlgG4oAekFQAhrhBdJ1WhygA3UQBsArhF5IA2jAC6A4VADGFAE4mIhMBQIBLXAHMFytVFCQoM4AAtoZEGwBfNjYDE3F8CgBbV3AINjdoAFkQJFimVjlRXlwVSIAjCBM+OTzeQmATO3tioJCRAqUKAHc0L2ajChUlfCgm6DsqQvQqEyjXHygAcj9eACJRWcmoO3KIUR6ZQghgYCrl4ChI8RVlJRAAfjZjXHLSeSheeARk1Mg0edmGZnZOGagPlByRSqdRQAAsAHZAkA

Upvotes: 0

Views: 47

Answers (1)

ABOS
ABOS

Reputation: 3821

Can you try

type KV<T> = {
  [K in keyof T]: {
    key: K; // any key of T
    value: T[K]; // corresponding value type of the key
  }
}[keyof T]

And use it like

const kv: KV<MyType> = {
  key: "a",
  value: 47
}

Upvotes: 3

Related Questions