如何创建TypeScript递归模板字面量类型?
实现递归模板字面量类型MyTypesWithDot
你可以通过递归模板字面量结合联合类型来实现需求,核心思路是用${MyType}.${...}的结构嵌套自身,确保每一段都是合法的MyType成员,且通过单个点连接:
type MyType = 'A' | 'B' | 'C'; // 递归定义:要么是 MyType. MyType,要么是 MyType. 已定义的合法嵌套结构 type MyTypesWithDot = `${MyType}.${MyType | MyTypesWithDot}`; // 测试用例验证 type Valid1 = 'A.B' extends MyTypesWithDot ? true : false; // true type Valid2 = 'A.B.C' extends MyTypesWithDot ? true : false; // true type Valid3 = 'A.A.A.B.C' extends MyTypesWithDot ? true : false; // true type Invalid1 = 'A.D' extends MyTypesWithDot ? true : false; // false(D不在MyType中) type Invalid2 = 'A..B' extends MyTypesWithDot ? true : false; // false(连续点) type Invalid3 = 'A.BB' extends MyTypesWithDot ? true : false; // false(BB不是合法MyType成员)
原理说明
- 基础匹配层:
${MyType}.${MyType}直接匹配两层合法成员的连接(比如'A.B'这类最短合法格式) - 递归扩展层:
${MyType}.${MyTypesWithDot}允许在已有的合法结构后继续追加MyType成员,实现任意深度的嵌套(比如'A.B.C'本质是A.${B.C},而B.C本身是符合MyTypesWithDot的结构) - 自动过滤非法场景:模板字面量的类型检查会严格匹配结构,只要某一段不是
MyType、出现连续点或格式错误,就不会被归为MyTypesWithDot类型
内容的提问来源于stack exchange,提问作者milkyway
相关产品推荐
相关产品推荐

