首页 > 其他分享 >[Typescript] @freeze decorator

[Typescript] @freeze decorator

时间:2024-04-07 17:23:32浏览次数:16  
标签:Typescript obj name value freeze will any 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) && shouldFreeze) {
                value = newValue;
                // Only freeze if newValue is not null or undefined
                if (newValue !== null && newValue !== undefined) {
                    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,obj,name,value,freeze,will,any,decorator
From: https://www.cnblogs.com/Answer1215/p/18119481

相关文章

  • TypeScript: pdf.js v4.0.379
     <!doctypehtml><html><head><metacharset="utf-8"> <metahttp-equiv="X-UA-Compatible"content="chrome=1"><metaname="viewport"content="width=device-width,initial-sc......
  • HOW - Typescript 类型声明文件
    目录一、背景二、如何添加类型定义支持智能提示方法一:使用JSDoc注释方法二:使用TypeScript编写类型声明文件.d.ts方法三:JSDoc注释转Typescript类型声明文件总结二、使用TypeScript编写类型声明文件1.创建类型声明文件2.编写类型声明2.1dec......
  • Vue3 + TypeScript + Vite 初始项目搭建(ESLint、Prettier、Sass、Stylelint、husky、p
    仓库地址仓库地址:https://gitee.com/tongchaowei/vue-ts-vite-template项目源码下载:https://gitee.com/tongchaowei/vue-ts-vite-template/releases全局安装pnpm包管理工具执行如下命令在系统全局安装pnpm包管理工具:npmipnpm-g使用Vite脚手架创建Vue3......
  • 浅谈TypeScript对业务可维护性的影响
    前言笔者认为,TypeScript是服务于业务的,核心就是提高代码的可维护性.TypeScript是把双刃剑,如果类型系统使用的不好,反而会阻碍开发,甚至最后就变成了anyScript.笔者最近在使用TypeScript的过程中,有了一点点微不足道的思考,想和大家分享、探讨.本文比较适合有真实Ty......
  • Vue3+TypeScript项目(SKU管理模块)
    一、SKU模块静态页面src\views\product\sku\index.vue<template><el-card><el-tableborderstyle="margin:10px0px"><el-table-columntype="index"label="序号"width="80px"></el-table......
  • HOW - Typescript 常用特性介绍
    目录一、目标二、常用特性介绍anyvsunknowntypevsinterface泛型:Generics1.函数的泛型2.接口、类、类型别名的泛型3.泛型约束:限制类型变量的取值范围交叉类型1.用法一:一个对象拥有多个对象的所有属性2.用法二:Mixin条件类型1.用法一:Non......
  • TS(TypeScript)— 搭建开发环境
    1.创建pakeage.jsonnpminit//自选参数npminit-y//默认参数 2.构造目录安装ts开发依赖npminstalltypescripttslint-g创建功能文件夹 初始化ts(安装typescript就可以使用tsc命令)生成tsconfig.json文件tsc--init 配置webpacknpminstallwe......
  • 前端开发中Vue3+Typescript使用装饰器出现错误一则
    今天开发公司项目时,使用TS装饰器遇到一个问题。当我写完装饰器代码后进入网页,控制台提示SyntaxError:Invalidorunexpectedtoken两个小时后的排查后发现是tsconfig.json的配置问题。如果tsconfig.json文件中没有指定target选项,TypeScript编译器会默认使用es5作......
  • typescript——4.类
    介绍传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。从ECMAScript6开始,JavaScript程序员将能够使用基于类的面向对象的方式。使用TypeScript,我......
  • typescript——3.接口
    接口初探接口:约束、限制下面通过一个简单示例来观察接口是如何工作的:functionprintLabel(labelledObj:{label:string}){console.log(labelledObj.label);}letmyObj={size:10,label:"Size10Object"};printLabel(myObj);类型检查器会查看printLa......