To using decorate, we can modifiy tsconfig.json:

{
"compilerOptions": {
...
"experimentalDecorators": true,
...
}
}

So for example we want to build a '@LogMethod' decorator, which arroding to the system logging level to decide whether should log the action.

enum LoggingLevel {
INFO,
WARNING,
DEBUG,
TRACE
}
const loggingLevel = LoggingLevel.DEBUG; class Database {
name = 'ABC'; @LogMethod(LoggingLevel.DEBUG)
saveData(data: any) {
console.log(`save user ${data.name} to the database ${this.name}`);
}
} const db = new Database();
db.saveData({name: 'zhentian'});

So for example, current is 'DEBUG' for the system, so when log level set to the 'DEBUG' or 'TRACE', action will be logged, 'INFO', 'WARNING' will be not.

Decorator:

which is simplya function return a meta function:

function LogMethod(level: LoggingLevel):Function {
return (target: any, propertyKey: string,
descriptor: PropertyDescriptor) => {
} }

If we log out each params:

'descriptor' is something we are looking for, 'descriptor.value' holding the function which is 'saveData' function, we can put into a variable:

const originalFunction:Function = descriptor.value;

Then we can create a new function to wrap this 'originalFunction' in order to provide some additional functionality:

        descriptor.value = function(...args:any[]) {
if (level <= loggingLevel) {
console.log(">> " + propertyKey + " " + JSON.stringify(args));
} originalFunction.apply(this,args);
};

Full code:

enum LoggingLevel {
INFO,
WARNING,
DEBUG,
TRACE
}
const loggingLevel = LoggingLevel.DEBUG; function LogMethod(level: LoggingLevel):Function {
return (target: any, propertyKey: string,
descriptor: PropertyDescriptor) => { const originalFunction:Function = descriptor.value; descriptor.value = function(...args:any[]) {
if (level <= loggingLevel) {
console.log(">> " + propertyKey + " " + JSON.stringify(args));
} originalFunction.apply(this,args);
}; } } class Database {
name = 'ABC'; @LogMethod(LoggingLevel.DEBUG)
saveData(data: any) {
console.log(`save user ${data.name} to the database ${this.name}`);
}
} const db = new Database();
db.saveData({name: 'zhentian'});

[Typescript] Build Method decorators in Typescript的更多相关文章

  1. [TypeScript] Stopping a TypeScript Build When Errors Are Found

    TypeScript will always compile even if there are ridiculous errors in your project. This lesson show ...

  2. [Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript

    Vue 2.2 introduced a simple dependency injection system, allowing you to use provide and inject in y ...

  3. 深入浅出TypeScript(2)- 用TypeScript创建web项目

    前言 在第一篇中,我们简单介绍了TypeScript的一些简单语法,那么如果我们只是简单使用TypeScript开发一个web项目,应该做哪些准备?接下来我们就结合TypeScript和Webpack ...

  4. [Typescript] Introduction to Generics in Typescript

    If Typescript is the first language in which you've encountered generics, the concept can be quite d ...

  5. 学习TypeScript,笔记一:TypeScript的简介与数据类型

    该文章用于督促自己学习TypeScript,作为学笔记进行保存,如果有错误的地方欢迎指正 2019-03-27  16:50:03 一.什么是TypeScript? TypeScript是javasc ...

  6. [TypeScript] Custom data structures in TypeScript with iterators

    We usually think of types as something that can define a single layer of an object: with an interfac ...

  7. [Typescript] Specify Exact Values with TypeScript’s Literal Types

    A literal type is a type that represents exactly one value, e.g. one specific string or number. You ...

  8. [TypeScript] Overload a Function with TypeScript’s Overload Signatures

    Some functions may have different return types depending on the types of the arguments with which th ...

  9. [TypeScript] Represent Non-Primitive Types with TypeScript’s object Type

    ypeScript 2.2 introduced the object, a type that represents any non-primitive type. It can be used t ...

随机推荐

  1. hadoop 使用java操作hdfs

    1.创建目录 import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.ha ...

  2. nodejs安装与概述

    第一部分:安装与测试 1 官方下载地址 https://nodejs.org/en/ 2 测试是否安装成功? window下打开CMD窗口   输入:node -v  => 显示安装的nodej ...

  3. [terry笔记]python购物程序

    如下是一个购物程序: 先输入工资,显示商品列表,购买,quit退出,最后格式化输出所买的商品. count = 0 while True: #做一个循环判断,如果输入的不是数字,基于提示,三次后退出 ...

  4. jquery在文本框之后添加红*

    var addHtml="<span class='text_red'>*</span>";function req(re){ if(re.parent(& ...

  5. hdu1290

    由二维的切割问题可知,平面切割与线之间的交点有关,即交点决定射线和线段的条数,从而决定新增的区域数. 当有n-1个平面时,切割的空间数为f(n-1).要有最多的空间数.则第n个平面需与前n-1个平面相 ...

  6. [NOIP2017] 逛公园 解题报告(DP)

    我很不想说 在我的AC代码上我打了表,但实在没有办法了.莫名的8,9个点RE.然而即便是打表...也花了我很久. 这大概是NOIP2017最难的题了,为了让不懂的人更容易理解,这篇题解会比较详细 我的 ...

  7. MYSQL主从复制搭建及切换操作(GTID与传统)

    结构如下: MYSQL主从复制方式有默认的复制方式异步复制,5.5版本之后半同步复制,5.6版本之后新增GTID复制,包括5.7版本的多源复制. MYSQL版本:5.7.20 操作系统版本:linux ...

  8. POJ 2502 Dijkstra OR spfa

    思路: 建完了图就是模板水题了 -.. 但是建图很坑. 首先要把出发点向地铁站&终点 连一条边 地铁站之间要连无向边 地铁站向终点连一条边 以上的边权要*0.006 两个地铁站之间要连无向边 ...

  9. 关于Tool接口--------hadoop接口:extends Configured implements Tool 和 ToolRunner.run

    我们在写Hadoop--map/reduce程序时,遇到使用按文件url来分析文件----------多表连接的DistributedCache方式,看不懂使用extends Configured i ...

  10. sqlserver 恢复模式及避免日志爆满的方法

    recovery simple 循环日志,空间自动回收,不可备份日志,恢复时仅能恢复到数据库备份时间点: 用于落地数据或测试环境或OLAP,不推荐用于生产OLTP 有时候distribution过大也 ...