【发布时间】:2021-03-29 22:51:10
【问题描述】:
我尝试使用花哨的 TypeScript 模板文字键入 REST API。我有一个适用于 const 字符串类型和 const Javascript 模板文字类型的系统,但不适用于具有未知值的 Javascript 模板文字。
考虑以下递归路径解析器。
type PathVariable = string;
type ExtractPathVariable<T extends string> = T extends `:${string}`
? PathVariable
: T;
type PathParts<Path extends string> = Path extends `/${infer Rest}`
? PathParts<Rest>
: Path extends `${infer Start}/${infer Rest}`
? [ExtractPathVariable<Start>, ...PathParts<`${Rest}`>]
: Path extends `${infer Item}`
? [ExtractPathVariable<Item>]
: never;
它在某些情况下给出了预期的结果
// A == ["short", "url", "path"]
type A = PathParts<"/short/url/path">;
const b = `/short/url/path` as const;
// B == ["short", "url", "path"]
type B = PathParts<typeof b>;
// C == ["short", "${y}", "path"]
type C = PathParts<"/short/${y}/path">;
const d = `/short/${45}/path` as const;
// D == ["short", "45", "path"]
type D = PathParts<typeof d>;
但是,我最感兴趣的案例(因为这就是我调用 API 的方式),它不起作用。
let y: unknown;
const e = `/short/${y}/path`;
// E == never
type E = PathParts<typeof e>;
有没有办法让PathParts<typeof e> 工作? E == ["short", string, "path"] 或 E == ["short", unknown, "path"] 的结果会很好。
【问题讨论】:
-
查看 TS4.3 的更新答案
标签: typescript template-literals