我想要达到的是:
type Post = {
id: number
title: string
author: {
name: string
}
comments: {
text: string
}[]
}
type ExtractPathExpressions<T> = ???
type Paths = ExtractPathExpressions<Post>
// expects above got a union --> 'id' | 'title' | 'author' | 'author.name' | 'comments' | `comments[${number}]` | `comments[${number}].text`
我知道这很不寻常...但是,有人知道ExtractPathExpressions
会是什么样子吗?
2条答案
按热度按时间iih3973s1#
这当然不是一个不寻常的任务,但它是一个复杂的递归任务,需要对不同的情况进行单独处理,其中属性:
1.是基本类型
1.是嵌套对象
1.是嵌套数组
第2种和第3种情况需要递归,因为这两种情况都可以包含其他嵌套对象和数组。
您希望创建所有可能的路径排列的 * 并集 *,因此在每一步,我们必须返回键本身和模板文字的并集,模板文字连接键和属性上递归
ExtractPathExpressions
的结果,除非它是基元类型。类型本身显然应该是一个Map类型(在下面的示例中,我选择了较新的键重Map特性),其键可以用于模板文本类型(
string | number | bigint | boolean | null | undefined
的并集),这意味着必须排除symbol
类型。下面是所需类型的外观:
测试:
Playground
smdncfj32#
我也遇到过类似的问题,但我在提出的解决方案
ExtractPathExpressions
中发现了一个小问题。如果你想得到一个数组的键,你将得到它的所有方法的键。
我修改了这个解决方案来处理数组并提取子类型,以使代码更容易阅读。你可以在这里看到我的解决方案。
完整代码:
示例:
希望我帮到你了!