根据子字符串键过滤打字稿类型

Hed*_*nto 2 typescript

假设我们有打字稿类型

type AllTypes = "hello.world"|"love.typescript"|"learn.typescript"|"love.stackoverflow"
Run Code Online (Sandbox Code Playgroud)

如何根据子字符串“typescript”从 AllTypes 中选择类型

jca*_*alz 7

您可以使用实用程序类型Extract<T, U>提取可分配给适当模式模板文字类型的AllTypes 联合成员(包含,如microsoft/TypeScript#40598中实现的那样): `${string}`

type AllTypes = "hello.world" | "love.typescript" | 
  "learn.typescript" | "love.stackoverflow";

type X = Extract<AllTypes, `${string}typescript${string}`>;
// type X = "love.typescript" | "learn.typescript"
Run Code Online (Sandbox Code Playgroud)

该类型`${string}typescript${string}`对应于包含 substring 的所有字符串"typescript",就像`${string}`对应于任何字符串(包括空字符串)一样。

Playground 代码链接