typescript - 使用 TS 文字类型,获取匹配多个模式与字符串文字联合的字符串的最直接方法是什么?
问题描述
假设我有以下工会:
type T = "a.success" | "a.failure" | "b.success" | "c";
我想获得一次匹配两个模式的所有字符串的联合 -${string}.success
并且${string}.failure
(在我的示例中,生成的联合将是 only MyUnion = "a"
)
我期待以下语法可以工作(因为它完全符合我想要的联合运算符,但不是交集):
type BothSuccessAndFailure <ID = T> = ID extends `${infer Base}.success` & `${infer Base}.failure`
? Base
: never;
但这总是解决never
,无论如何。将其中一个切换infer Base
到infer Base2
也无济于事。有没有办法使这项工作?
这里有两种可行的方法,但并不像我想要的那样干净:
// This gets a bit messy with increasing number of patterns to match and
// Prettier breaking each of them into four lines.
type Success<ID = T> = ID extends `${infer Base}.success` ? Base : never;
type Failure<ID = T> = ID extends `${infer Base2}.failure` ? Base2 : never;
type BothSuccessAndFailure
// I thought of this one while authoring this question and it's acceptable for me, but
// I still find the syntax a bit confusing, and many nested ternaries slightly annoying
type BothSuccessAndFailure<ID = T> = ID extends `${infer Base}.success`
? `${Base}.failure` extends T
? Base
: never
: never;
还是有可能制作一个GetStringsPresentWithAllOfSuffixes<SourceUnion, SuffixUnion>
通用的?
解决方案
推荐阅读
- reactjs - React Navigation 4.x 到 React Navigation 5.x
- regex - pdfgrep 模式包含/排除换行符
- python - 动手机器学习代码不适用于 Jupyter,但适用于 Google。为什么?
- javascript - 在 R Shiny 中观察另一个事件时控制嵌入的 YouTube 视频
- asp.net-web-api - 在请求正文中传递 Odata 查询选项
- php - 学说锁表
- javascript - 定义元素之前的控制台输出错误Javascript
- face-recognition - 使用 TFLITE 量化 MobileFaceNet 失败
- r - 我可以像使用 ffmpeg 一样使用 R 来修剪视频吗?
- database - 如何使用 GraphQL 只返回我需要的数据?