microsoft / microsoft/TypeScript
Cannot infer `thisArg` argument type of `Function.bind` for functions with a `this` type consisting of generic functions
还没有人认领这个 Issue。
- 主要语言
- Go
- 星标
- 111k
- 派生
- 14.3k
- 平均合并
- 2 天 4 小时
- 30 天内合并 PR
- 132
描述
Bug Report
Consider a function like-
declare function callback<T>(this: CallbackCtx<T>): void;
Where CallbackCtx is an object containing generic function(s)-
interface CallbackCtx<T> {
onsuccess: (x: T) => number;
onerror: (err: any) => void;
}
For such a function, that has its this type set to an object containing generic function(s), Function.bind cannot infer the type of thisArg (from the first overload) correctly.
If the type parameter to .bind is explicitly specified (by substituting the generic function type to be a concrete type) - it works fine.
The type of thisArg inferred by typescript automatically, is CallbackCtx<unknown>.
It should be noted that if CallbackCtx contains only non function-like property(s) - the types are inferred correctly. As seen in this playground
🔎 Search Terms
bind, generic, function
🕗 Version & Regression Information
4.2.3
⏯ Playground Link
Playground link with relevant code
💻 Code
interface CallbackCtx<T> {
onsuccess: (x: T) => number;
onerror: (err: any) => void;
}
declare function callback<T>(this: CallbackCtx<T>): void;
declare const ctx: CallbackCtx<string>;
callback.bind(ctx);
// ^ CallbackCtx<string> is not assignable to CallbackCtx<unknown>
callback.bind<(this: CallbackCtx<string>) => void>(ctx);
// ^ Works fine when manually substituting the generic type of the function
🙁 Actual behavior
The line callback.bind(ctx); produces errors
🙂 Expected behavior
The line callback.bind(ctx); should infer the type of callback correctly by substituting the generic type with the help of the type of ctx and should not produce errors
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从链接的 TypeScript Playground 和 callback.bind(ctx) 示例开始,将其与显式类型化的 .bind 调用进行比较。跟踪包含泛型函数属性的 this 类型如何为 Function.bind 推断。完成的标准是:推断出的上下文使用来自 ctx 的 CallbackCtx<string>,并且未添加类型注解的调用不会产生错误。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- typescript
- 领域
- compilers
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100