Skip to content

TypeScript: No way to extend the LocatorOrString type for custom locators #2797

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
danielrentz opened this issue Feb 2, 2021 · 0 comments · Fixed by #2798
Closed

TypeScript: No way to extend the LocatorOrString type for custom locators #2797

danielrentz opened this issue Feb 2, 2021 · 0 comments · Fixed by #2798

Comments

@danielrentz
Copy link
Contributor

danielrentz commented Feb 2, 2021

What are you trying to achieve?

Define and use a custom locator in TypeScript code.

What do you get instead?

Custom locators cannot be added to the type definitions, leading to compiler errors when trying to use them in any methods with LocatorOrString parameters.

e2e/tests/xyz.ts:166:59 - error TS2322: Type 'string' is not assignable to type '(locator: LocatorOrString) => Locator'.

166     I.seeElement({ custom: "xyz", option: true });

Details

  • CodeceptJS version: 3.0.4
  • TypeScript version: 4.1.3

Proposed Solution

The way to add custom types from user code is declaration merging (as already done with the Methods interface). However, the types ILocator and LocatorOrString are fixed union types that cannot be extended. Therefore I suggest to add a CustomLocators interface that can be extended from outside and that will be used to build the LocatorOrString type.

Example:

interface CustomLocators { }

type LocatorOrString = string | ILocator | Locator | CustomLocators[keyof CustomLocators];

The property keys used in the interface are arbitrary (only the property types will be used), but should reflect the keys used in the locator object. After that, it is possible to extend the CustomLocators interface:

declare global {
    namespace CodeceptJS {
        interface CustomLocators {
            custom: { custom: string; option?: boolean };
        }
    }
}
danielrentz added a commit to danielrentz/CodeceptJS that referenced this issue Feb 2, 2021
DavertMik pushed a commit that referenced this issue Feb 5, 2021
* #2797 +CustomLocators interface

* add documentation

Co-authored-by: Daniel Rentz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant