In TypeScript, it is currently possible to get the union type of all the "keys" of an interface, something like:
interface foo {
name: string;
age: number;
}
function onlyTakeFooKeys(key: keyof foo) {
// do stuff with key
}
And the compiler will enforce that onlyTakeFooKeys
can only be called with either name
or age
.
My use case is that I need to get a union type of the all the types of an interface/object's member. In the given interface foo
example, I'm expecting something like this:
some_operator foo; //=> string | number
Is this currently achievable?
Assuming the interfaces have arbitrary number of members which makes hard-coding impossible. And that this needs to be done at compile time.
You can define ValueOf<T>
like this:
type ValueOf<T> = T[keyof T]
using lookup types to index into T
with keyof T
. In your case, you could do ValueOf<foo>
to produce string | number
.
This has almost certainly been asked and answered before; my powers of search are failing me at the moment. This answer is a duplicate of this answer, but the question as stated is a bit different (as it needed to constrain the key with the value type for that key).
Hope that helps. Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With