Search code examples
typescripttypescript-typings

How to setup context for `this` keyword in typescript


I have following to migrate a codebase to typescript & there is a structure which is as follows :

  1. Simple schema defination for mongo collection
  2. A separate file where all helpers are present for instance of particular collection's element

In code it would look like this : Schema.ts:

const schema = new SimpleSchema({......});
type schemaType = { ..... }; // This is added by me as simple schema doesn't give typescript types

Now I have helpers.ts:

const helpers = {
  helper1() { this.prop1 }; // prop1 is defined in `schemaType`
  helper2() { this.prop2 * this.prop3 }; // prop2 and prop3 are defined in `schemaType`
}

const helpersType = typeof helpers; // This will give all inferred types for helpers.

Now problem is that this.prop1, this.prop2 and this.prop3 will throw typescript error as it does not know that the object's context will have those props sooner or later.

So how do I approach it?

I tried to add types to helpers object but it would require either full type defination or no types at all for inferred type compliation to work.


Solution

  • You can give TypeScript a hint about the context in which a function will be executed by giving a type to this in the arguments like this:

    interface Schema {
        prop1: string;
        prop2: number;
        prop3: number;
    }
    
    const helpers = {
        helper1(this: Schema) { return this.prop1 },
        helper2(this: Schema) { return this.prop2 * this.prop3 },
    }
    
    const schema: Schema = {
        prop1: 'prop1',
        prop2: 2,
        prop3: 3,
    }
    
    const result = helpers.helper2.call(schema);
    
    console.log(result);
    

    TypeScript playground