|
|
|
|
|
by amitport
1100 days ago
|
|
Well there are 2 issues: (1) imperative style mutation of the prototype is runtime dependent, and typescript can't really rely on runtime behavior. (2) Foo has two incompatible types in JS, it is both `(s) => void` and `new (s) => Foo`, typescript by default will assume the first signature (which is usually what people want). In any case, you can specify the types (though in 99% of the cases, just use a class): interface Foo {
s: string;
bar(): void;
}
const Foo = function(this: Foo, s: string) {
this.s = s;
} as {
new (s: string): Foo;
(this: Foo, s: string): void;
};
Foo.prototype.bar = function(this: Foo) {
console.log(this.s);
}
const baz = new Foo('Hello');
baz.bar()
|
|
While that is a fair statement, I've been reading a lot of Typescript code lately and it seems in 99% of cases the selected solution is to use top level functions and globals to avoid the nesting hell class introduces, albeit introducing the global hell in the process. In practice, 'just use a class' doesn't overcome the human element.
Javascript was on the right track originally, but then veered off into the weeds for some reason. I appreciate you pointing out how it can be done. Although the solution is very much second class citizen, sadly. This certainly isn't going to wean developers away from global hell. Hopefully Javascript/Typescript can make some strides in improving this going forward.