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. 虚拟机安装mac

    没成功,把几篇不错的文章先记录下地址 http://bbs.pcbeta.com/forum.php?mod=viewthread&tid=1437039 http://bbs.pcbeta. ...

  2. js数组并集,交集,差集

    js数组并集,交集,差集的计算方式汇总 一. new Set 方式实现 这种方式实现起来比较简单,原理就是参考new Set可以去重的功能 ,关于去重可以点击 https://www.haorooms ...

  3. Ubuntu17.04安装WineQQ7.8及微信

    安装qq2012成功,但是提示版本过低,qq登录失败. 安装WineQQ WineQQ7.8下载 安装依赖软件,方法来源网上 32位ubuntu:sudo apt install libgtk-3-0 ...

  4. Android 多分辨率自适应总结

    这周的工作对Android项目多分辨率自适应进行调整.故对这方面知识进行不断的尝试学习.Android项目刚開始做的时候一定养成编程习惯,全部资源调用放在value中.统一命名以及管理.总结了下面内容 ...

  5. 正睿NOIP赠送附加赛1

    T1:math 题目链接: http://zhengruioi.com/contest/156/problem/471 题解: 先讲讲我的乱搞做法.对于前面70%,我跑了背包.因为背包有后效性...我 ...

  6. 15-11-23:system指令

    CMD命令:开始->运行->键入cmd或command(在命令行里可以看到系统版本.文件系统版本) 1. appwiz.cpl:程序和功能 2. calc:启动计算器 3. certmgr ...

  7. Wordcount 和 shuffle的流程

  8. Spark SQL - 对大规模的结构化数据进行批处理和流式处理

    Spark SQL - 对大规模的结构化数据进行批处理和流式处理 大体翻译自:https://jaceklaskowski.gitbooks.io/mastering-apache-spark/con ...

  9. Visual Studio蛋疼问题解决(1)

    监视变量显示未定义标识符: VS2012在编译的时候采用了较快的编译模式,所以有些变量就显示未定义了.  解决方案:  项目->属性->c/c++->优化->改为禁用/OD  ...

  10. 【原创】RPM安装软件时解决依赖性问题(自动解决依赖型)

    满足以下3个条件才能自动解决依赖性: 1.使用rpmdb -redhat(在安装时会自动弹出依赖性错误) 2.所有互相依赖的软件都必须在同一个目录下面. 3.调用-aid参数.