You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Search Terms: class override method parameters covariance contravaraiance variance
Code
classExample{foo(maybe: number|undefined){}str(str: string){}compare(ex: Example){}}classOverrideextendsExample{foo(maybe: number){}// Bad: should have error.str(str: 'override'){}// Bad: should have error.compare(ex: Override){}// Bad: should have error.}constex: Example=newOverride();ex.foo(undefined);ex.str('anything');ex.compare(newExample());
Expected behavior:
Definition of each overridden method should have an error. Parameter is contravariant instead of covariant.
Actual behavior:
No errors at compile time. Even with strictFunctionTypes enabled.
It was a known design issue that method-style syntax doesn't enforce variance checks. If we did so, it would break all instances of things like Dog[] being assignable to Animal[], or the subclassing of HTMLDivElement from HTMLElement.
DanielRosenwasser
changed the title
Overridden method parameters are not checked for covariance
Overridden method parameters are not checked for parameter contravariance
Feb 24, 2018
TypeScript Version: 2.7.0-rc
Search Terms: class override method parameters covariance contravaraiance variance
Code
Expected behavior:
Definition of each overridden method should have an error. Parameter is contravariant instead of covariant.
Actual behavior:
No errors at compile time. Even with
strictFunctionTypes
enabled.Playground Link:
https://www.typescriptlang.org/play/#src=class%20Example%20%7B%0D%0A%20%20%20%20foo(maybe%3A%20number%20%7C%20undefined)%20%7B%20%7D%0D%0A%20%20%20%20str(str%3A%20string)%20%7B%20%7D%0D%0A%20%20%20%20compare(ex%3A%20Example)%20%7B%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20Override%20extends%20Example%20%7B%0D%0A%20%20%20%20foo(maybe%3A%20number)%20%7B%20%7D%20%2F%2F%20Bad%3A%20should%20have%20error.%0D%0A%20%20%20%20str(str%3A%20'override')%20%7B%20%7D%20%2F%2F%20Bad%3A%20should%20have%20error.%0D%0A%20%20%20%20compare(ex%3A%20Override)%20%7B%20%7D%20%2F%2F%20Bad%3A%20should%20have%20error.%0D%0A%7D%0D%0A%0D%0Aconst%20ex%3A%20Example%20%3D%20new%20Override()%3B%0D%0Aex.foo(undefined)%3B%0D%0Aex.str('anything')%3B%0D%0Aex.compare(new%20Example())%3B
Related Issues:
The text was updated successfully, but these errors were encountered: