I’m having a hard type figuring out how to define a type as the union of all possible values from a predefined object type.
Assume we have an autogenerated type Person
that looks like this:
type Person = {
favouriteColor: string
age: number
female: boolean
}
How does one use the Person
type to create a union type equal to string | number | boolean
?
In my use case, the type Person
is autogenerated. I’m using Ramda’s map function on an object, to apply a function to each of the object’s values:
import { map } from 'ramda'
classroom.people.forEach(person =>
// Ramda’s `map` is applied to a `block` object here:
map<Person, Person>(property => {
// The type definitions for Ramda are not sufficiently strong to infer the type
// of `property`, so it needs to be manually annotated.
return someFunction(property)
}, person)
)
The behavior I’m looking for is essentially equivalent to keyof
— but as far as I know there is no valueof
in TypeScript. What would an equivalent implementation look like?
Thank you very much!
Edit: ordinarily, the solution would be as suggested by @kaya3: type ValueOf<T> = T[keyof T]
. However, upon closer inspection, my situation seems to be troubled by the following:
type PersonCommonFields = {
age: number,
name: string
}
type PersonFragment =
| { favouriteColor: string }
| { female: boolean }
| { eyeColor: Color }
| { born: Date }
type Person = PersonCommonFields & PersonFragment
In this case, ValueOf<Person>
as defined above returns number | string
, i.e. only the values from PersonCommonFields
, ignoring PersonFragment
. The expected result for this example would be number | string | boolean | Color | Date
.
Would there be an alternative approach to tackle this situation?
Many (many!) thanks in advance!