Skip to content

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

Closed
@danielrentz

Description

@danielrentz

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 };
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions