[Typescript] @freeze decorator

function freeze(config?: { unless: () => boolean }) {
    return function(target: any, propertyKey: string) {
        let value: any;
        const getter = function () {
            return value;
        };
        const setter = function (newValue: any) {
            const shouldFreeze = !(config?.unless?.() === true);
            if (value === undefined || value === null) {
                value = newValue;
                // Only freeze if newValue is not null or undefined
                if (newValue !== null && newValue !== undefined && shouldFreeze) {
                    Object.freeze(value);
                }
            }
        };

        // Delete the original property and re-define it with getter and setter
        if (delete target[propertyKey]) {
            Object.defineProperty(target, propertyKey, {
                get: getter,
                set: setter,
                enumerable: true,
                configurable: true
            });
        }
    };
}

 

Usage:

class Example {
    @freeze() // No configuration passed, so it will always freeze the property
    alwaysFrozenProperty: any;    
    
    @freeze({ unless: () => false }) // This will freeze the property
    myProperty: any;

    @freeze({ unless: () => true }) // This will not freeze the property due to the unless condition
    anotherProperty: any;
}

const obj = new Example();
obj.alwaysFrozenProperty = { name: "Frozen" };
obj.alwaysFrozenProperty.name = "Modified"; // No effect, as the object is frozen
console.log(obj.alwaysFrozenProperty); // Outputs: { name: "Frozen" }

obj.myProperty = { name: "Test" };
obj.myProperty.name = "Changed"; // This will have no effect because `myProperty` is frozen
console.log(obj.myProperty); // Outputs: { name: "Test" }

obj.anotherProperty = { name: "Initial" }; // This will not freeze the property
obj.anotherProperty.name = "Modified"; // This will modify the property because it's not frozen
console.log(obj.anotherProperty); // Outputs: { name: "Modified" }

 

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-04-07 [Javascript] Improve performance of Array.reduce
2021-04-07 [AWS] Lab: Docker and CodeCommit Part 1
2021-04-07 [AWS] Lab: Docker with CodeCommit & CodeBuild Part2
2019-04-07 [Algorithm] Longest Substring Without Repeating Characters?
2016-04-07 [Angular 2] Using Promise to Http
2016-04-07 [Angular 2] *ngFor with index
点击右上角即可分享
微信分享提示