Let's analyze the code snippet below:
export class BaseClass<T> {
property = this.buildProperty();
buildProperty(){
return someBuilder<T>();
}
}
Through TypeScript, the type of property
is automatically determined based on the result of buildProperty()
To improve readability, I decided to initialize the property within the constructor. Here is the refactored code here:
export class BaseClass<T> {
property: ReturnType<BaseClass<T>['buildProperty']>;
constructor(){
this.property = this.buildProperty();
}
buildProperty(){
return someBuilder<T>();
}
}
While this approach is technically correct, I find it redundant to repeat the class type twice as in BaseClass<T>
This led me to explore if there is a simpler way using this
. However, my attempt at rewriting the property's type did not yield the desired outcome:
property: ReturnType<this['buildProperty']>;
Is there a more concise method to achieve this?