feihcsim
feihcsim

Reputation: 1552

What is TypeScript's ThisType used for?

TypeScript comes with an interface ThisType. I couldn't find much documentation on it, so I'm wondering: what is it used for? How do I use it? How does it work?

Upvotes: 15

Views: 9073

Answers (1)

Tyler Church
Tyler Church

Reputation: 669

ThisType is documented here: https://www.typescriptlang.org/docs/handbook/utility-types.html#thistypet (thanks to @axiac for linking that in the comments)

However, the example the docs use feels a bit convoluted to me. This is the easiest way I've found to think about it:

If you add & ThisType<T> to the type of an object, the functions within that object will have T as the type used for this, where T can be whatever type you define. This is helpful if you can't otherwise specify what this should be through the normal TypeScript mechanisms (it's not a class, etc.)

If we imagine a world where we're writing some code that registers some helper functions, you could write it like this:

interface HelperThisValue {
    logError: (error: string) => void;
}

let helperFunctions: { [name: string]: Function } & ThisType<HelperThisValue> = {
    hello: function() {
        this.logError("Error: Something went wrong!"); // TypeScript successfully recognizes that "logError" is a part of "this".
        this.update(); // TS2339: Property 'update' does not exist on HelperThisValue.
    }
}

registerHelpers(helperFunctions);

As I've indicated in the comments above, TypeScript now knows the correct type, and will give errors if we misuse it.

Note that like all of TypeScript's typings, using ThisType has no effect on the resulting JavaScript code. There must be code elsewhere that ensures that when the members of helperFunctions get called, the proper this value is set (e.g. through use of Function.bind, Function.apply, Function.call, etc.)

Upvotes: 27

Related Questions