I'm building Page Objects for my automated tests, and I'm doing something like this:
abstract class Page {
selectors: {
// Here are selectors which are common to all my pages
genericSelector: "...",
commonContainer: {
aButton: "..."
}
}
// methods that are common to all my pages
}
class MyPage extends Page {
// Here I want my page specific selectors
// *plus* my generic selectors
selectors: {
...this.selectors,
mySpecificSelector: "..."
}
}
The above code works fine at run-time: I can correctly use all my selectors in my code. However, Typescript complains on MyPage.ts
that:
Property 'selectors' in type 'MyPage' is not assignable to the same property in base type 'Page.
Basically because TS doesn't know that I'm spreading the base class prop into the subclass.
Now, the following is what I tried:
One additional note
My type for the selector property looks like this:
type Selector = string | SelectorFactory | { selector: string, type: "css" | "xpath" }
type SelectorFactory = (...args: any[]) => string;
type SelectorTree = { [k: string]: SelectorTree | Selector }
What I tried
First attempt
class MyPage extends Page {
selectors: {
...this.selectors as InstanceType<typeof Page>["selectors"]
}
}
This, then complains:
'selectors' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
So I have to do:
selectors: SelectorTree = // ...
Then I'm back to square one, as it complains that it is missing some properties from the base class. If I add : SelectorTree
to my base class, it then doesn't complain, but I don't get proper intellisense and I even get errors (for example if I try to call a function from my selectors properties, I can't).
Second attempt
I could, I guess, have my selectors
member of the base Page
class be static. Then I could do:
selectors: {
...Page.selectors,
mySpecificSelector: "..."
}
This works, but, well, I now actually have an extra static member that I did not want to have.
Third attempt, aka “I give up”
I could separate the members and have something like baseSelectors
on my Page
class and then I could either use them as they are within the sub-class, or spread them into my selectors
object.
But this feels like a defeat.