microsoft / microsoft/TypeScript

Ensure forward-compatibility of callbacks

未关闭
#42,579 15 条评论 48 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Suggestion

🔍 Search Terms

strict callback arguments, too many arguments warning, option

✅ Viability Checklist

My suggestion meets these guidelines:

  • 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

Edit: My original suggestion was unworkable. This is a second attempt.

const nextFrame = new Promise(requestAnimationFrame);

The above results in requestAnimationFrame being called with two arguments rather than the one it accepts. This is fragile, since, in future, a second argument may be added to requestAnimationFrame which makes the above code behave differently.

This problem is worse when it comes to browser-provided functions, as those change with new browser versions, and don't rely on an app redeploy.

This can be worked around using never:

declare function requestAnimationFrame(callback: FrameRequestCallback, _: never): number;

…but it makes for a messy auto-complete, as the 'never' arg shows up.

A solution would be some way to mark a function as "cannot be assigned to a function type with more parameters". This would allow library authors to make this assertion if they want to reserve additional params for future use, and this assertion could be added to DOM functions like requestAnimationFrame.

💻 Use Cases

I wrote a blog post about the risks with this pattern, including a section on how TypeScript doesn't prevent it https://jakearchibald.com/2021/function-callback-risks/

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 requestAnimationFrame 示例开始,查看链接的 TypeScript Design Goals 以及 callback-argument 行为。比较 never-parameter 变通方案与提议的 function-type assertion;只有在达成一项既能保留现有运行时行为、又能规定如何编写和检查库声明的设计后,才算完成。

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

评估

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

把新 issue 发到你的邮箱

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