In our codebase we use a navigator and builder patterns pretty extensively to abstract away assembling hierarchical objects. At the heart of this is a Navigator class which we use to traverse different classes. I'm currently attempting to migrate this to typescript but am struggling to type it to leverage the power of typescript.
I think the core of my problem is that I can't use this as the default value for a generic on a class e.g. class Something<T = this>, or that I can't overload the class to somehow conditionally set the types of class properties. Can you provide any insights into how I might be able to type the Navigator (and builder classes) below?
// I guess what I'd like to do is
// class Navigator<BackT = this> but that's not allowed
class Navigator<BackT> {
// It's this 'back' type I'll like to define more specifically
// i.e. if back is passed to the constructor then it should be 'BackT'
// if back is not passed to the constructor or is undefined, it
// should be 'this'
back: BackT | this;
constructor(back?: BackT) {
this.back = back || this;
}
}
class Builder1<BackT> extends Navigator<BackT> {
builder1DoSomething() {
// Do some work here
return this;
}
}
class Builder2<BackT> extends Navigator<BackT> {
withBuilder1() {
return new Builder1(this);
// Also tried the following, but I got the same error:
// return new Builder1<this>(this);
}
builder2DoSomething() {
// Do some work here
return this;
}
}
// This is fine
new Builder1().builder1DoSomething().builder1DoSomething();
new Builder2()
.withBuilder1()
.builder1DoSomething()
// I get an error here becuase my types are not specific enough to
// let the complier know 'back' has taken me out of 'Builder1' and
// back to 'Builder2'
.back.builder2DoSomething();