Catch unsafe use of "this" in TypeScript functions

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:19] 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.

[00:35] 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.

[00:49] 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.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today