我有一个困难的类型,想出如何将类型定义为来自预定义对象类型的所有可能值的合并。
假设我们有一个自动生成的类型Person,如下所示:
type Person = {
  favouriteColor: string
  age: number
  female: boolean
}如何使用Person类型创建与string | number | boolean相等的联合类型
在我的用例中,Person类型是自动生成的。我在对象上使用Ramda的地图函数,将一个函数应用于每个对象的值:
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)
)据我所知,据我所知,keyof - but在TypeScript中没有valueof。等效的实现是什么样子的?
非常感谢!
编辑:通常情况下,解决方案将如@kaya3 3:type ValueOf<T> = T[keyof T]所建议的那样。然而,仔细观察后,我的情况似乎受到以下情况的困扰:
type PersonCommonFields = {
  age: number,
  name: string
}
type PersonFragment =
  | { favouriteColor: string }
  | { female: boolean }
  | { eyeColor: Color }
  | { born: Date }
type Person = PersonCommonFields & PersonFragment在本例中,上面定义的ValueOf<Person>返回number | string,即只返回来自PersonCommonFields的值,而忽略PersonFragment。本例的预期结果将是number | string | boolean | Color | Date。
会否有另一种方法来处理这种情况?
很多(很多!)提前谢谢!
发布于 2020-02-06 01:45:55
对于联合类型,ValueOf<T> = T[keyof T]类型不能正常工作,因为keyof不会在联合中分发。例如,keyof ({foo: 1} | {bar: 2})类型是never而不是'foo' | 'bar'。
相反,我们可以使用分布条件类型,它确实分布在联合中(顾名思义)。
type ValueOfUnion<T> = T extends infer U ? U[keyof U] : never
type Test = ValueOfUnion<Person>
// Test = string | number | boolean | Color | Date操场连接
https://stackoverflow.com/questions/60084968
复制相似问题