typescript - 根据数组值获取联合类型的子集
问题描述
给定以下类型:
// All possible values
type Alphabet = 'a' | 'b' | 'c' | 'd' | 'e' // ... etc
// Value transformation
type ComputedAlphabet<A extends Alphabet> = {[k in A]: true}
let x: ComputedAlphabet<'a' | 'b'>; // it correctly expects: {a: true, b: true}
我想要一个函数类型,它接受一个字母数组并计算它们的值:
type TransformAlphabet=(chars: Alphabet[]) => ComputedAlphabet<how to get subset of Alphabet based on `chars`???>
理想情况下,我想编写这样的调用并正确推断类型:
let transform: TransformAlphabet
transform(['a']) // should infer {a: true} as a return type
当然,我尝试的第一件事是使用泛型,但不知道如何在生成正确类型的同时使泛型类型可选:
type TransformAlphabet<A extends Alphabet>=(chars: A[]) => ComputedAlphabet<A>
如果我A
在调用时手动传递泛型类型,这在我的情况下是不切实际的。
解决方案
推荐阅读
- hadoop - 如何在直线开始时删除 ADD jar 语句
- android - 如何更改 android compose TextFeild 的内容填充?
- java - 在 AsyncTask 中更新后自动/立即更新进度条
- postgresql - 来自 pg_range 和 pg_type 的查询不断占用我服务器的资源 - postgresql
- node.js - 将 cURL 命令转换为 JavaScript
- r - stringr 提取正则表达式未按预期工作
- android - 如何使用 Glide 获取网络图像的高度和宽度?
- database - 无法创建分片集合
- php - PHP和MySql,登录查询
- laravel - 在 cpanel 上上传项目时 laravel 错误