Explained in another response, the use of const
in ES6 does not prevent objects from being modified, but rather only stops reassignments.
To globally prohibit parameter reassignments, one can employ TSLint's no-parameter-reassignment
rule.
If the goal is to prevent object modifications during runtime, one should utilize Object.freeze
. At compile time, this restriction can be imposed using the Readonly
mapped type. However, if the types are compatible, this method will not have any effect:
interface compareTo {
(v1: Readonly<Square>, v2: Readonly<Square>): number;
}
const foo: compareTo = (a: Square, b: Square) => {
a.area = 0;
return 1;
}
Typically, it is not the role of an interface to dictate how a function functions internally; it simply defines its interface. Therefore, it would be represented as follows:
interface compareTo {
(v1: Square, v2: Square): number;
}
const foo: compareTo = (a: Readonly<Square>, b: Readonly<Square>) => {
a.area = 0; // error
return 1;
}
This approach will succeed when types are inferred from a generic type, meaning that the type of a
is not specified in the implementation of compareTo
:
interface compareTo<T = Readonly<Square>> {
(v1: T, v2: T): number;
}
const foo: compareTo = (a, b) => {
a.area = 0; // error
return 1;
}