Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 985 of the free egghead.io lessons, plus get TypeScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Catch unsafe use of "this" in TypeScript functions

1:04 TypeScript lesson by

this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately there is a TypeScript compiler flag noImplicit this that can help catch unsafe usages so beginners don't get caught off guard.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately there is a TypeScript compiler flag noImplicit this that can help catch unsafe usages so beginners don't get caught off guard.

Here I have a simple function, fu, which logs this to the console. If I go ahead and call this function from the root of the file, you can see that this actually points to the node js global variable. I can prove this by simply checking if this is equal to global, and it is.

Now if I go ahead and create a bar variable that has fu as a member and now call bar.fu, you can see that within the function this will no longer point to the global variable and instead it points to bar.

This is because for simple functions, in JavaScript and TypeScript the value of this changes based on how the function is called. This is why there is a TypeScript compiler option called noImplicitThis.

As soon as you set that to true, any unsafe usages of this immediately become errors. If you still want the unsafe behavior, you are free to annotate this as any for a given function and you can see that the errors go away.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?