[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" }
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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