Description
First of all: Please excuse me if this issue is a duplicate of some sort, but I've searched for quite some time for a similar issue or at least an answer to the following question/bug/proposal and found nothing.
If I specify that a function has a certain (customized) 'this' type I expect that the function has full access to protected or even private fields of passed instances. Reason being that due to JavaScripts dynamic nature and it's capability to overwrite the this
pointer, a function that is freestanding can still act like an extension method to a class.
Below you can find a simple JavaScript-like style of extending a existing class, which fails in TypeScript, because it strictly forbids access to private and protected fields outside of the actual class:
class MyClass {
protected p: number;
constructor() {
this.p = 123;
}
}
interface MyClass {
extension(p: number): void;
}
MyClass.prototype.extension = function (this: MyClass, p: number) {
// FAILS with:
// error TS2445: Property 'p' is protected and only accessible within class 'MyClass' and its subclasses.
this.p = p;
}
const instance = new MyClass();
instance.extension(456);
I realize that some kind of "official" class extension technique will get into TypeScript sooner or later, but all of the proposals I've seen extend the actual JavaScript language with new keywords. This question/bug/proposal here though, basically does exactly the same as the existing extension proposals but within the boundaries of the JavaScript language (apart from the existing language extensions for the type checker).
I thus humbly suggest to loosen this strict access control and allow us to write extension methods to at least some extend before v2.0 is finally released.