能否用TypeScript实现提取动态import路径的工具类型?
TypeScript提取动态导入路径与页面ID的实现方案
一、提取动态导入路径的工具类型
TypeScript无法直接从模块实例的typeof mod中提取导入路径(模块实例的类型仅包含导出内容,不携带路径信息),但可以从动态导入函数的类型入手实现需求:
// 工具类型:从动态导入函数中提取导入路径 type ImportPath<T extends () => Promise<any>> = T extends () => Promise<import(infer P)> ? P : never; // 使用示例 const importModule = () => import('./path/to/module'); type modImportPath = ImportPath<typeof importModule>; // 类型为 './path/to/module'
原理:TypeScript在处理import(infer P)的类型推断时,会将动态导入的路径字面量绑定到类型变量P上,从而提取出路径字符串。
二、推断页面ID的实现方案
基于上述ImportPath工具类型,可以进一步从页面导入路径中提取页面ID:
// 提取导入路径 type ImportPath<T extends () => Promise<any>> = T extends () => Promise<import(infer P)> ? P : never; // 从路径中提取页面ID(适配 './pages/XXX' 格式的路径) type PageId<T extends () => Promise<any>> = ImportPath<T> extends `./pages/${infer Id}` ? Id : never; // 实际使用:必须添加 `as const` 保留字面量类型 const routes = [ { Page: () => import('./pages/LandingPage'), route: '/' }, { Page: () => import('./pages/AboutPage'), route: '/about' } ] as const; // 推断页面ID type LandingPageId = PageId<typeof routes[0]['Page']>; // 类型为 'LandingPage' type AboutPageId = PageId<typeof routes[1]['Page']>; // 类型为 'AboutPage'
关键注意事项
- 必须为
routes添加as const断言,否则TypeScript会将数组元素的类型合并为联合类型,无法单独提取每个页面的导入路径。 - 路径匹配模板(
./pages/${infer Id})需要与用户实际的页面路径格式对应,如果路径格式不同(如src/pages/XXX或../pages/XXX),需调整模板字符串的匹配规则。 - 仅支持静态可解析的导入路径,如果路径是动态生成的(如
import(./pages/${pageName})),TypeScript无法推断出具体的路径和页面ID。
内容的提问来源于stack exchange,提问作者brillout
相关产品推荐
相关产品推荐

