'Is that possible to assign a type to this (cucumber world object)

Is that possible to have the completion with this world object ? I mean...

I have a class named Application

export class Application {

  constructor() {}

  async run() { 
   // do stuff to run the app
  }

  get applicationDescription(): string {
    return 'The best application in the world';
    }
}

In my step

Given('I run my application', {timeout: 10000}, async function() {
   this.app: Application = new Application();
   await this.app.run(); <-- here when I write this.app. I want to see that run is a 
                             accessible method
});



Solution 1:[1]

In the most basic sense, this is world within a step definition (you must NOT use arrow functions, as you have shown):

Given('I run my application', {timeout: 10000}, async function() {
   this.app = new Application();
   await this.app.run();
});

When done in this fashion you are just monkey patching properties onto the world object, so its working on the basis that its type is any, so you don't get type safety/autocomplete in your IDE.

You can use a custom world to get those benefits:

class MyWorld extends World {
  app: Application

  constructor(props: IWorldOptions) {
    super(props)
  }
}

setWorldConstructor(MyWorld)

Given('I run my application', this: MyWorld, {timeout: 10000}, async function() {
   this.app = new Application();
   await this.app.run();
});

Note that the second param is this: MyWorld, which is allowed in typescript to provide a type override for the this. It must come before any other params. If you omit it, this is still typed as Cucumbers World so you're back to any.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dave Meehan