Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time.
For example, let's create an interface:
interface freeze{
frozen: boolean;
}
Now, let's define a deep freeze function:
function deepFreeze<T>(obj: T) {
var propNames = Object.getOwnPropertyNames(obj);
for (let name of propNames) {
let value = (obj as any)[name];
if (value && typeof value === "object") {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
If we attempt something like this:
function shouldntWork(): freeze
{
let mutableFreeze: freeze = { frozen:false}
let immutableFreeze = deepFreeze(mutableFreeze);
return immutableFreeze;
}
I understand that this behavior is not a bug, but I am wondering if there is an eslint rule or similar mechanism to prevent the overwrite of types. Because if I were to do something like this:
function other() {
let something = shouldntWork();
something.frozen = true;
console.log(something);
}
This would lead to a runtime crash, even though I want the error to be caught at compile time.
Without specifying :freeze, TypeScript would infer the correct readonly type and provide a compile-time error.
You can test this on the TypeScript playground: here