Typescript - 从另一个联合类型的字段值中获取联合类型

标签 typescript

在 Typescript 中,是否可以从另一个联合类型的字段值中获取一个联合类型?

type MyUnionType = 
  | { foo: 'a', bar: 1 }
  | { foo: 'b', bar: 2 } 
  | { foo: 'c', bar: 3 }

// can I generate this automatically? 
// i.e. a union of the possible values of foo in MyUnionType?
type Foos = 'a' | 'b' | 'c'

我希望 Pick<MyUnionType, 'foo'>可能会这样做,但它不太有效 - 它返回我想要的类型但嵌套在 foo 下字段:{ foo: 'a' | 'b' | 'c' }

最佳答案

类型 Foos = MyUnionType['foo'] works只要每个类型都有一个 foo 字段:

type MyUnionType = 
  | { foo: 'a', bar: 1 }
  | { foo: 'b', bar: 2 } 
  | { foo: 'c', bar: 3 }

type FooType = MyUnionType['foo']
// FooType = "a" | "b" | "c"

如果您需要通过异构联合类型进行分发,您可以 filter向下到联合字段中的那些类型:

type PickField<T, K extends string> = T extends Record<K, any> ? T[K] : never;

然后你可以use :

type MyUnionType = 
  | { foo: 'a', bar: 1 }
  | { foo: 'b', bar: 2 } 
  | { foo: 'c', bar: 3 }
  | { bar: 4 }

type FooType = MyUnionType['foo']
// Property 'foo' does not exist on type 'MyUnionType'. :-(

type FooType2 = PickField<MyUnionType, 'foo'>
// type FooType2 = "a" | "b" | "c"

type PickField<T, K extends string> = T extends Record<K, any> ? T[K] : never;
// Alternatively, you could return `undefined` instead of `never`
// in the false branch to capture the potentially missing data

关于Typescript - 从另一个联合类型的字段值中获取联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57640575/

相关文章:

javascript - Typescript rxjs 可观察数组连接

javascript - Angular 2+ 从 http 请求返回变量或映射

typescript - 箭头样式用户定义的类型防护?

Angular 2 @ViewChild 不工作。无法读取未定义的属性 "title"

typescript - Nexus Prisma - 如何在全局范围内使用 crud 处理 createdAt 和 updatedAt?

javascript - 如何在不添加一些组件或模块的情况下构建 Angular 应用程序?

typescript - Webpack 中 Typescript 的源映射(使用 webpack-dev-server 时看不到源映射)

typescript - 在 Electron 的预加载脚本中使用 typescript

javascript - Angular2 - 防止复选框被选中

javascript - 属性管道不适用于类型 "OperatorFunction<unknown, [unknown, boolean, any]>"