microsoft / microsoft/TypeScript

Lazily evaluated template literal types

未关闭
#43,335 12 条评论 66 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

Suggestion

Template literal types seem to be resolved immediately, which makes the combinatorics blow up and the whole thing much less useful than it would seem to be at first.

For example I can't even represent a type equals to 5 consecutive digits with the current system without getting a "too complex" error:

type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type UUID = `${Digit}${Digit}${Digit}${Digit}${Digit}`;

The current system may be more composable than regexes, but if it's not even able to represent something like /\d{5}/ I'd argue that's not a replacement for it at all.

The suggestion is that there's no need to resolve all the possible combinations at all, but a divide and conquer approach should be implemented where each little piece of the template literal does it's job individually and when all little pieces match than the whole thing matches.

🔍 Search Terms

  • template literal
  • lazy

✅ Viability Checklist

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Evaluate template literal types lazily to not make the combinatorics blow up. Meaning that each little piece of the template literal should be its own little function that performs some type matching internally, so there's no need to resolve all the possible combinations at all.

📃 Motivating Example

I can't even represent the equivalent of /\d{5}/ currently.

type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type UUID = `${Digit}${Digit}${Digit}${Digit}${Digit}`;

💻 Use Cases

For example creating a type for UUID strings, which are a fairly common thing.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中起到推动作用的 TypeScript 示例开始:一个由 Digit 联合类型构成的五位数字模板字面量类型。研究编译器对模板字面量类型的求值和匹配行为;完成的标准是,该类型可以被表示和使用,而不会触发当前的 "too complex" 错误,同时保留模板字面量类型的匹配功能。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。