MST

星途 面试题库

面试题:TypeScript 模板字面量类型实现复杂字符串校验及类型推导

有一个场景,需要处理文件路径字符串。路径格式为:根目录('src' 或 'dist')/模块名(由字母、数字和下划线组成)/文件名(以 '.ts' 或 '.js' 结尾)。请使用 TypeScript 的模板字面量类型实现对这种文件路径字符串的校验,并且基于传入的合法路径字符串,推导出根目录、模块名和文件名的类型。编写相关的类型定义和一个示例函数,该函数接收合法路径字符串并返回包含这三个部分的对象。
34.0万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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);