You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:01:01