type RootDir ='src' | 'dist';
type ModuleName = string & { __brand: 'ModuleName' };
type FileName = string & { __brand: 'FileName' };
type ValidFilePath<S extends string> =
S extends `${RootDir}/${infer M extends string & /^[a-zA-Z0-9_]+$/}/${infer F extends string & (`.ts` | `.js`)}`
? {
rootDir: RootDir;
moduleName: M;
fileName: F;
}
: never;
function parseFilePath<S extends string>(path: S): ValidFilePath<S> {
const parts = path.split('/');
return {
rootDir: parts[0] as RootDir,
moduleName: parts[1] as ModuleName,
fileName: parts[2] as FileName
} as ValidFilePath<S>;
}
// 示例使用
const filePath: 'dist/utils/helper.ts' = 'dist/utils/helper.ts';
const result = parseFilePath(filePath);
console.log(result.rootDir);
console.log(result.moduleName);
console.log(result.fileName);