getter, accessor, this, generic
Currently accessor declarations do not support generics at the declaration site. The error returned is An accessor cannot have type parameters.ts(1094). Currently the accessor can implement generic declaration via the enclosing class. The goal would be to allow for the accessor to support a generic this at the declaration site.
The use case is to allow for more expressive setter/getter declarations, in line with how method declarations currently work.
Below is an example of defining the constraints of this at the accessor site, to determine if an inherited accessor method is valid by the shape of the subclass.
class Base {
get left<T extends { _left: string}>(this: T) {
return this._left;
}
get right<T extends { _right: string}>(this: T) {
return this._right;
}
}
...
class Left extends Base {
_left: string = '';
}
new Left().left; // OK
new Left().right; // Errors
...
class Right extends Base {
_right: string = '';
}
new Right().right; // OK
new Right().left; // Errors
...
class Both extends Base {
_right: string = '';
_left: string = '';
}
new Both().right; // OK
new Both().left; // OK
This pattern can currently be emulated by converting the accessors into standard methods
class Base {
getLeft<T extends { _left: string}>(this: T) {
return this._left;
}
getRight<T extends { _right: string}>(this: T) {
return this._right;
}
}
...
class Left extends Base {
_left: string = '';
}
new Left().getLeft(); // OK
new Left().getRight(); // Errors
...
class Right extends Base {
_right: string = '';
}
new Right().getRight(); // OK
new Right().getLeft(); // Errors
...
class Both extends Base {
_right: string = '';
_left: string = '';
}
new Both().getRight(); // OK
new Both().getLeft(); // OK
My suggestion meets these guidelines:
I would love that feature, too. I would like to use getters for "modifiers" without arguments, that return a modified object of the same type. E.g.:
class A {
protected val: string;
public withString<T extends A>(this: T, val: string): T {
this.val = val;
return this;
}
public get And<T extends A>(this: T): T {
return this;
}
public get inUpperCase<T extends A>(this: T): T {
this.val = this.val.toUpperCase();
return this;
}
public toString(): string {
return this.val;
}
}
const a = new A().withString("test").And.InUpperCase;
console.out(a.toString()); // TEST
In this particular case, we could return type A, but as soon as we start with inheritance:
class B extends A {
}
const b = new B().toUpperCase;
the type of b would be converted to A.
Most helpful comment
I would love that feature, too. I would like to use getters for "modifiers" without arguments, that return a modified object of the same type. E.g.:
In this particular case, we could return type A, but as soon as we start with inheritance:
the type of b would be converted to A.