首页 > 解决方案 > 使用 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 Baseinfer 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>通用的?

标签: typescripttypescript-genericstemplate-strings

解决方案


推荐阅读