typescript - 获取嵌套值作为类型
问题描述
考虑以下类型定义,
type Parent = {
children: Child[]
}
type Child = {
label: string
}
const parent: Parent = {
children: [
{ label: 'label1' },
{ label: 'label2' }
]
}
现在,如果我想生成一个基因类型,其中包含标签值作为键和任何值,是否可以使用泛型来做到这一点?请注意,我只考虑编译时对象。
type Labels = {
label1: any,
label2: any
}
解决方案
您可以将Child
and 定义Parent
为泛型类型,其中K extends string
用作泛型约束以正确推断字符串文字:
type Parent<K extends string> = {
children: Child<K>[]
}
type Child<K extends string> = {
label: K
}
type Labels<P extends Parent<any>> = P extends Parent<infer K>
? { [Key in K]: string } : never;
然后,您可以使用辅助函数从字符串文字中自动推断标签键(而不是在定义parent
为值时手动键入它们):
function Parent<K extends string>(parent: Parent<K>) {
return parent;
}
const p1 = Parent({
children: [
{ label: 'label1' },
{ label: 'label2' }
]
})
现在你需要的只是一个辅助类型,它使用推理和对象映射,转换类型中的键Labels
:
type Labels<P extends Parent<any>> = P extends Parent<infer K>
? { [Key in K]: string } : never;
type Labels1 = Labels<typeof p1>;
// Labels1 now is `{ label1: string; label2: string }`
看看它在行动@游乐场
推荐阅读
- flutter - 如何用颤振密码保护文件
- python - 如何使用 Matplotlib 错误条图形进行绘图
- sympy - sympy.symbols 和 sympy.Symbol 之间的区别
- python - 如何使用 urllib3 发布 x-www-form-urlencoded 数据
- python - IDLE和python不同,无法正确安装模块
- google-apps-script - 开发一个日历和电子表格脚本的项目,可以吗?
- sql-server - 如何在 SQL Server 2017 中将列添加到复制表的主键
- python - Solr Prepared 语句,按数据中心进行工作负载隔离
- web-scraping - 从 HTML 网站提取或提取数据时出现 VBA 代码错误
- deep-learning - 使用 TFrecords 在 TPU 中使用图像分割的训练损失是 Nan