Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a union type of an interface's member's types

Tags:

typescript

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.

like image 397
benjaminz Avatar asked Mar 07 '23 09:03

benjaminz


1 Answers

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.

like image 173
jcalz Avatar answered Mar 12 '23 17:03

jcalz