Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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 Jun 9 by avibootz
...