Vern Jensen
Vern Jensen

Reputation: 3560

Get TypeScript to catch 'this' type mismatch errors?

Let's say I have a module with a function like so:

export module Network
{
    export function savePrefs( globals:Globals )
    {
       // [save globals.prefs to the database...]
    }
}

And originally I have the code that calls it is part of the Globals class, so it calls the above method using:

Network.savePrefs(this);

since, being an instance method inside the Globals class, the 'this' variable refers to a Globals instance. But later I decide to move that method to a module, and forget to change 'this':

export module Utils
{
    upgradePrefs(globals:Globals)
    {
        // [... upgrade stuff....] //
        Network.savePrefs(this); // OOPS!
    }
}

TypeScript does not generate an error for this.

I'd like to get TypeScript to give me an error when this happens, as 'this' does not match the required type (Globals) for the method being called. Is that possible with some kind of compiler configuration option?

Upvotes: 0

Views: 144

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30929

It sounds like you're probably missing the noImplicitThis compiler option, which causes references to this that are not in a context with a known this type (such as a class) to generate an error instead of having type any. You might want to turn on strict (which includes noImplicitThis and a number of other useful options) and then turn off any options that are part of strict that you don't want.

Upvotes: 1

Related Questions