实现说明
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);