← 中文资源

简体中文版本

OmitThisParameter 剥离已绑定的接收者类型

用 OmitThisParameter 去掉函数类型里的显式 this 参数,让 .bind() 后的回调既能放进无接收者队列,又能在编译期拦住未绑定的裸方法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

first call: api:2
second call: api:5
counter total: 5

实现说明

OmitThisParameter 剥离已绑定的接收者类型以函数 incrementBy为骨架。

使用要点

  • 构造上就无依赖——没有注册表,没有锁文件条目。
  • 每一步打印都带着自己的标签:first call:、second call:、counter total:。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件在加载时定义 incrementBy。

入口签名:function incrementBy(this: Counter, step: number)

核心语句

return `${this.label}:${this.count}`;
this.count += step;

代码示例

interface Counter {
  label: string;
  count: number;
}

function incrementBy(this: Counter, step: number): string {
  this.count += step;
  return `${this.label}:${this.count}`;
}

// OmitThisParameter drops the leading `this: Counter` constraint after .bind()
type BoundIncrement = OmitThisParameter<typeof incrementBy>;

const queue: BoundIncrement[] = [];
const apiHits: Counter = { label: 'api', count: 0 };

const boundAdd: BoundIncrement = incrementBy.bind(apiHits);
queue.push(boundAdd);

// Unbound `incrementBy` cannot enter `queue` because `this: Counter` is still required
// queue.push(incrementBy);

console.log('first call:', queue[0](2));
console.log('second call:', queue[0](3));
console.log('counter total:', apiHits.count);