示例工程 05-function-types-overloads
05-function-types-overloads/03-this-parameter/src/main.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// 演示:this 参数是编译期约束,运行时被擦除
export interface Counter {
count: number;
}
export function increment(this: Counter, by: number): number {
this.count += by;
return this.count;
}
export interface CounterWithMethod extends Counter {
increment: typeof increment;
}
export function makeCounter(): CounterWithMethod {
return { count: 0, increment };
}
export function run(log: (msg: string) => void = console.log): string[] {
const counter = makeCounter();
const lines = [
`method:${counter.increment(2)}`,
`call:${increment.call(counter, 3)}`,
`count:${counter.count}`,
];
for (const line of lines) {
log(line);
}
return lines;
}