typescript - 如何从 TypeScript 的接口中提取“路径表达式”?
问题描述
我想要实现的是:
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 和 3 需要递归,因为两者都可以包含其他嵌套对象和数组。
您想要创建所有可能的路径排列的联合,因此在每一步,我们必须返回键本身和连接键的模板文字的并集以及ExtractPathExpressions
属性上的递归结果,除非它是原始类型.
类型本身显然应该是映射类型(在下面的示例中,我选择了更新的键重新映射功能),其键可用于模板文字类型(的联合string | number | bigint | boolean | null | undefined
),这意味着symbol
必须排除该类型。
这就是所需类型的样子:
type ExtractPathExpressions<T, Sep extends string = "."> = Exclude<
keyof {
[P in Exclude<keyof T, symbol> as T[P] extends any[] | readonly any[]
?
| P
| `${P}[${number}]`
| `${P}[${number}]${Sep}${Exclude<
ExtractPathExpressions<T[P][number]>,
keyof number | keyof string
>}`
: T[P] extends { [x: string]: any }
? `${P}${Sep}${ExtractPathExpressions<T[P]>}` | P
: P]: string;
},
symbol
>;
测试一下:
type Post = {
id: number
title: string
author: {
name: string
}
comments: {
text: string,
replies: {
author: {
name: string
}
}[],
responses: readonly { a:boolean }[],
ids: string[],
refs: number[],
accepts: readonly bigint[]
}[]
}
type Paths = ExtractPathExpressions<Post>;
//"id" | "title" | "author" | "comments" | "author.name" | `comments[${number}]` | `comments[${number}].text` | `comments[${number}].replies` | `comments[${number}].responses` | `comments[${number}].ids` | `comments[${number}].refs` | `comments[${number}].accepts` | `comments[${number}].replies[${number}]` | `comments[${number}].replies[${number}].author` | `comments[${number}].replies[${number}].author.name` | ... 4 more ... | `comments[${number}].accepts[${number}]`
推荐阅读
- flutter - 如何通过 TapGestureRecognizer 获取 TextSpan 的信息
- c# - 以编程方式调用 ASMX 中的所有操作
- node.js - 无法在 Ubuntu 终端中运行 NPM 或 ng build 或 Apache
- javascript - TypeScript - 自定义类元素的 Array.map
- elasticsearch - 使用 JMeter 向 Elasticsearch 进行身份验证
- c# - ADAL AcquireTokenAsync 不想要父窗口
- haddock - 为什么我的 Haddock 生成的文档主页的签名部分是空的?
- reactjs - 解析文件时出现意外令牌 (8:8)
- c++ - 将 _m256i 转为 int 数组
- c# - C# - 将字符串数组转换为多维字符串数组