New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type System Bug: Function.prototype.call variance error #52239
Comments
Nothing to do with variance in this case. Methods don't have automatic |
Found the relevant issue: #35451 |
True, and I did not know this was possible. Though, the type-checker still accepted code that is not valid. It should either not accept it when calling the prototype or when declaring the function and calling the private method. Codeinterface Animal {
getAttention(): void;
}
class Cat implements Animal {
private meow(): void {
console.log("meow!");
}
getAttention(this: this) {
this.meow();
}
}
class Dog implements Animal {
private bark(): void {
console.log("bark!");
}
getAttention(this: this) {
this.bark();
}
}
function animalGetsAttention(it: Animal, method: (this: Animal) => void) {
method.call(it);
}
// Argument of type '(this: Cat) => void' is not assignable to parameter of type '(this: Animal) => void'.
animalGetsAttention(new Dog(), Cat.prototype.getAttention);
If the compiler accepts invalid code for performance reasons, then why is there no |
Just for future reference, this is unavoidable in general; it's explicitly called out in the design goals for TS that the compiler tries to "strike a balance between correctness and productivity". Plus the type system seeks to be friendly to idiomatic JS patterns as possible, which as you can probably imagine is its own entire can of worms. Tradeoffs will inevitably be made.
Interestingly, discussion in #6739 suggests this behavior was intended to be behind a flag (so not the default), but the perf implications were ultimately considered severe enough that it wasn't considered worth the tradeoff even then. |
So this is a "Won't fix", then I will close this issue. |
Relevant non-goal from the TypeScript Design Goals:
|
Considering that #35451 was closed as |
Bug Report
🔎 Search Terms
(is:open label:Bug) function, call, prototype method, variance
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
The code passed the type checker and compiled even though it is incorrect and fails at runtime.
🙂 Expected behavior
The compiler should not allow calling the method; the type system should not allow generalizing
this
in this case (as far as I understand it, as Cat.prototype.getAttention should requirethis
to extendCat
and notCat
to extendAnimal
).I believe this has to do with Co- and Contravariance.
The text was updated successfully, but these errors were encountered: