4

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.

benjaminz
  • 3,118
  • 3
  • 35
  • 47
  • Possible duplicate of [Is there a \`valueof\` similar to \`keyof\` in TypeScript?](https://stackoverflow.com/questions/49285864/is-there-a-valueof-similar-to-keyof-in-typescript) – jcalz Apr 20 '18 at 18:19

1 Answers1

7

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.

jcalz
  • 264,269
  • 27
  • 359
  • 360