5 ms·
TypeScript catches a lot, but "this" bugs are still one of the most common things it misses. For example, when factoring a method into a free function, I'll oft
by ridiculous_fish 10y ago
TypeScript catches a lot, but "this" bugs are still one of the most common things it misses. For example, when factoring a method into a free function, I'll often miss a this:
function hypot(x:number, y:number) {
return Math.sqrt(this.x * this.x + this.y * this.y)
}
TypeScript does not warn about this case.
- farnsworth 10y agoCheck out the option "noImplicitThis" in TS2, for this exact case. It will ban using `this` when it's implicitly `any`. I agree that it was much needed!
- ridiculous_fish 10y agoGreat addition! Thanks for pointing it out.
- hkjgkjy 10y agoA very happy way to live as a Javascript coder is to avoid the `this` keyword, in my experience. You really don't need it. Instead write this function as (x, y) => Math.sqrt(x*x + y*y) That can never have any state bugs, because it's a pure function (just like you can never have type errors with a sufficiently good type system). And you might be interested in the native JS function (since ES6) called Math.hypot. Happy hacking :-)