How to enforce immutability to prevent the modification of values in TypeScript

1 Answer

0 votes
// Immutable User in TypeScript 

"use strict";

/*
    This version ensures ALL exceptions activate at runtime.

    - TypeScript is bypassed using (User as any)
    - JavaScript strict mode is enabled
    - Object.freeze() enforces runtime immutability
    - deepFreeze() protects nested objects
*/

// Deep freeze for runtime immutability
function deepFreeze<T>(obj: T): T {
    Object.freeze(obj);

    for (const key of Object.keys(obj)) {
        const value: any = (obj as any)[key];
        if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
            deepFreeze(value);
        }
    }
    return obj;
}

// Immutable User type (compile-time)
type UserType = {
    readonly id: number;
    readonly name: string;
};

// Create immutable User object
const User: UserType = deepFreeze({
    id: 42,
    name: "Sophia"
} as const);

console.log("ID:", User.id);
console.log("Name:", User.name);

// Attempt 1: modify id
try {
    (User as any).id = 100; // Cannot assign to read only property 'id'
} catch (e: any) {
    console.log("Blocked:", e.message);
}

// Attempt 2: modify name
try {
    (User as any).name = "Pet"; // Cannot assign to read only property 'name'
} catch (e: any) {
    console.log("Blocked:", e.message);
}

// Attempt 3: add new property
try {
    (User as any).age = 30; // Cannot add property age, object is not extensible
} catch (e: any) {
    console.log("Blocked:", e.message);
}

// Attempt 4: delete property
try {
    delete (User as any).name; // Cannot delete property 'name'
} catch (e: any) {
    console.log("Blocked:", e.message);
}



/* 
run:

ID: 42
Name: Sophia
Blocked: Cannot assign to read only property 'id' of object '#<Object>'
Blocked: Cannot assign to read only property 'name' of object '#<Object>'
Blocked: Cannot add property age, object is not extensi

*/

 



answered 7 hours ago by avibootz
...