Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Catch unsafe use of "this" in TypeScript functions

    Basarat Ali SyedBasarat Ali Syed

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.