如何为.ext.ts模块声明Correct<T>类型替代自动检测的T类型?
解决TypeScript识别.extts模块类型为Correct的方案
你可以通过TypeScript的通配符模块声明结合模板字符串类型推导来实现需求,核心是从.ext.ts后缀中提取原始文件路径,获取其自动检测的类型T,再包裹为Correct<T>。
步骤1:定义基础类型
先确保你的Fixed和Correct类型已正确定义(若未定义,可在类型文件中补充):
// 替换成你的Fixed类型实际实现逻辑 type Fixed<T> = T extends string ? `${T}_processed` : T; // 你提供的Correct类型 type Correct<T> = {[K in keyof T]: Fixed<T[K]>};
步骤2:编写模块类型声明
创建一个类型定义文件(比如ext-typings.d.ts),写入以下内容:
type Fixed<T> = /* 你的Fixed类型实现 */; type Correct<T> = {[K in keyof T]: Fixed<T[K]>}; // 声明所有.extts后缀的模块 declare module "*.ext.ts" { // 从.ext.ts路径中提取基础部分,拼接成对应的.ts文件路径 type OriginalFilePath = `${string}.ext.ts` extends `${infer BasePath}.ext.ts` ? `${BasePath}.ts` : never; // 导入原始.ts文件的自动检测类型 import type * as OriginalModule from OriginalFilePath; // 将原始类型转换为Correct<T> type CorrectedModule = Correct<OriginalModule>; // 导出转换后的模块实例 const module: CorrectedModule; export default module; // 处理命名导出:转换所有命名导出的类型 export type { [K in keyof OriginalModule]: Fixed<OriginalModule[K]> }; export const { [K in keyof OriginalModule]: Fixed<OriginalModule[K]> }; }
步骤3:配置TypeScript
确保你的tsconfig.json包含这个类型文件,保证路径解析正常:
{ "compilerOptions": { "typeRoots": ["./node_modules/@types", "./src/types"], "moduleResolution": "NodeNext" }, "include": ["src/**/*", "src/types/ext-typings.d.ts"] }
完成配置后,当你导入.ext.ts文件时,TypeScript会自动将其类型识别为Correct<T>,其中T是对应.ts文件的原始自动检测类型。
内容的提问来源于stack exchange,提问作者Vasile Lixcode
相关产品推荐
相关产品推荐

