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

如何为Function.prototype.bind等效函数编写精确TypeScript类型签名?

TypeScript 泛型 Bind 函数实现(仅绑定 this)

如果你需要一个仅绑定函数this上下文、不预设调用参数的泛型bind函数,以下是符合TypeScript类型系统的实现方案:

类型定义与函数实现

// 定义绑定后的函数类型:检查thisArg是否匹配原函数的this类型
type BindThis<T extends (...args: any[]) => any, This> = 
  This extends ThisParameterType<T> 
    ? (...args: Parameters<T>) => ReturnType<T> 
    : never;

function bindThis<T extends (...args: any[]) => any, This>(
  fn: T,
  thisArg: This
): BindThis<T, This> {
  return function(this: This, ...args: Parameters<T>) {
    return fn.apply(thisArg, args);
  } as BindThis<T, This>;
}

核心逻辑说明

  • BindThis 类型通过ThisParameterType<T>获取原函数T的this约束,确保传入的thisArg类型完全匹配,否则返回never触发编译期错误。
  • 函数实现使用apply绑定指定的thisArg,同时保留原函数的所有参数和返回值类型。
  • 类型断言as BindThis<T, This>帮助TypeScript正确推导返回函数的类型。

使用示例

class MyClass {
  value = 42;
  
  getValue(): number {
    return this.value;
  }
  
  add(a: number, b: number): number {
    return this.value + a + b;
  }
}

const obj = new MyClass();

// 未绑定this的函数,直接调用会报错
const unboundGet = obj.getValue;
// unboundGet(); // Error: Cannot read property 'value' of undefined

// 绑定this后可正常调用,类型完全匹配
const boundGet = bindThis(obj.getValue, obj);
console.log(boundGet()); // 输出 42

const boundAdd = bindThis(obj.add, obj);
console.log(boundAdd(10, 20)); // 输出 72

类型安全校验

如果传入的thisArg不符合原函数的this类型,TypeScript会直接在编译阶段抛出错误:

// 类型错误:{ value: number; } 无法赋值给 MyClass 类型
const wrongBound = bindThis(obj.getValue, { value: 100 });

内容的提问来源于stack exchange,提问作者John Gietzen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:14:54