Reputation: 44
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!
Upvotes: 0
Views: 47
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