It appears that in typescript, it is possible to remove the readonly modifier from a type through a simple assignment:
function updateValue(x: { readonly content: string }) {
x.content = "new content"; // This operation would normally fail
modifyContent(x); // Surprisingly, this works without any issues
}
function modifyContent(x: { content: string }) {
x.content = "new content";
}
Is there a risk of accidentally mutating a readonly field with this approach? Have I misunderstood the proper usage of the readonly keyword in typescript? Are there stricter alternatives available in typescript to prevent such unauthorized modifications?
UPDATE: Acknowledging the existing behavior, here's a workaround that may be helpful in certain scenarios, although not foolproof:
type Immutable<T> = { __mutable: true } & { [P in keyof T]: T[P] };
type Readonly<T> = T extends Immutable<any> ? { readonly [P in Exclude<keyof T, "__mutable">]: T[P] } : never;
type SomeType = Immutable<{
content: string;
}>;
function updateContent(x: Readonly<SomeType>) {
let y: SomeType = x; // This will trigger a compile-time error
y.content = "new content";
}