假设我们有打字稿类型
type AllTypes = "hello.world"|"love.typescript"|"learn.typescript"|"love.stackoverflow"
Run Code Online (Sandbox Code Playgroud)
如何根据子字符串“typescript”从 AllTypes 中选择类型
您可以使用实用程序类型仅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}`对应于任何字符串(包括空字符串)一样。
| 归档时间: |
|
| 查看次数: |
500 次 |
| 最近记录: |