TypeScript Version: 2.0.3, 2.1.0-dev.20160927
Code
// A *self-contained* demonstration of the problem follows...
'use strict';
interface RO { readonly x: number; }
interface RW { x: number; }
const ro: RO = Object.freeze({ x: 3 });
function modifyX(input: RW) {
input.x = 5;
}
// No type error
// Throws exception
modifyX(ro);
Expected behavior:
The call modifyX(ro) should give a type error, as ro has a readonly property but the interface to modifyX requires a modifiable field.
Actual behavior:
No type error.
To avoid breaking every definition file in the world, the opposite of readonly is sort of "unknown", not "must be mutable". readonly doesn't affect type relationships, it just disallows the line ro.x = 1; in that sample.
OK, I understand that backwards compatibility is important, but I do think that it limits the usefulness of readonly somewhat. I would like to use it particularly to rule out changing frozen objects (which are frozen for immutability requirements). I had hoped to be able to use readonly to do so, but if the behavior above is as intended, I don't see how I can achieve that.
we have talked about --strictReadOnlychecks in the past that will treat "unknown" as "read-write". I do not think we have an issue tracking this though.
I would definitely love to see a --strictReadOnlychecks option.
@mhegazy would it be apropriate for me to open a suggestion for this? (I am obviously +1 on this ;) )
I have opened #11481 as a suggestion to add strictReadonlyChecks
closing in favor of #11481
Most helpful comment
we have talked about
--strictReadOnlychecksin the past that will treat "unknown" as "read-write". I do not think we have an issue tracking this though.