Closed c7hm4r closed 6 years ago
This is working as intended. The --strictFunctionTypes
mode doesn't affect properties declared using method syntax. See #18654 for the rationale.
To simulate properties with strict type checking currently it seems to be the simplest solution to define a getter and setter, going without a more concise syntax. For example:
interface IBox<T> {
getValue: () => T;
setValue: (value: T) => void;
}
Instead of:
interface IBox<T> {
value: T;
}
To implement the above interface and achieve type safety I think it is necessary to either:
In my opinion it is too restrictive that the contravariance of a function depends on whether it is a method or a property. I would be pleased if strict type checking for methods is introduced in TypeScript in the future—I am used to C#.
Unfortunately the DOM itself is constructed in a way where it can't be correctly typed without either adding write-only properties (ugh) or introducing semantics for inheritance-isn't-subtyping. All the element event methods have a callback that passes the element type itself, which means they can be incorrectly invoked through a supertype reference.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.7.0-dev.20171216
Code
Compiler options:
Expected behavior:
Compilation should fail at assignments 2, 3, 4 and 5.
Actual behavior:
Compilation only fails at assigments 3 and 5.
tsc
output:Additional Notes:
The expected behavior handles contravariance correctly, the actual behavior not.
This bug could be part of the more general issue “Covariance / Contravariance Annotations”, but a full covariance / contravariance implementation is probably not necessary to fix this bug. It would probably also be fixed if “Proposal: covariance and contravariance generic type arguments annotations” is implemented.