CodexBloom - Programming Q&A Platform

TypeScript class method returning this type but causing implementing method chaining

πŸ‘€ Views: 26 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
typescript class method-chaining

I'm sure I'm missing something obvious here, but I'm working with an scenario with method chaining in my TypeScript class. I have a class `Calculator` where I'm trying to implement fluent interfaces. My methods are supposed to return `this`, but when I chain them, I'm getting unexpected results. Here's a simplified version of my code: ```typescript class Calculator { private value: number; constructor() { this.value = 0; } public add(num: number): this { this.value += num; return this; } public subtract(num: number): this { this.value -= num; return this; } public multiply(num: number): this { this.value *= num; return this; } public getValue(): number { return this.value; } } const calc = new Calculator(); const result = calc.add(5).subtract(3).multiply(2).getValue(); console.log(result); // Expected output: 4 ``` However, when I run this code, I get the output as `0` instead of `4`. I've tried debugging by checking the value after each operation, but it seems that the `value` is never updated in the method chain. I also ensured that the return type for each method is `this`, but it doesn’t seem to help. I’m using TypeScript version 4.4.3. Any thoughts on what might be going wrong here? Could it be an scenario with how TypeScript handles the `this` type in chained methods? Any help would be greatly appreciated!