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. crm 系统项目(三) 自动分页

    crm 系统项目(三) 自动分页 需求: 1. 做一个自动分页, 每15条数据1页 2. 让当前页数在中间显示 3. 上一页, 下一页 注意情况: 1.总页数 小于 规定显示的页数 2. 左右两边极值 ...

  2. js兼容性——获取当前浏览器窗口的宽高

    通过onresize事件 window.onresize = function () { document.title = client().width + " "+ client ...

  3. java方法名的重载

    方法的重载:方法名相同,参数不同,按照参数类型进行匹配 创建一个Simple 类,然后定义了两个方法 package cuteSnow; public class Simple { // 方法的重载, ...

  4. 【转载】linux下的usb抓包方法

    1 linux下的usb抓包方法 1.配置内核使能usb monitor: make menuconfig                   Device Drivers -->        ...

  5. 字符串的HashCode可能相同

    字符串的HashCode可能相同 学习了:http://blog.csdn.net/hl_java/article/details/71511815

  6. cocos2d-x-3.3rc2-003 cocos中的引用计数和自己主动释放池

    点击打开链接

  7. 【Android】Android程序自己主动更新

    App自己主动更新的步骤可分为三步: 检查更新(假设有更新进行第2步,否则返回) 下载新版的APK安装包 安装APK 以下对这三步进行解释.当中会穿插相应代码.App自己主动更新的这三步所有被封装到了 ...

  8. intellij idea 13&amp;14 插件推荐及高速上手建议 (已更新!)

    早些年 在外企的时候,公司用的是intellij idea ,当时也是从eclipse.MyEclipse转过去的非常是不习惯. 用了一周明显感觉爱上它了.由于它非常智能,并且能纠正你非常多不好的习惯 ...

  9. 实现 jstl标签foreach 功能

    jsp 页面 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEn ...

  10. 十分钟掌握diff&patch用法

    作为程序员,了解diff&patch命令是非常必要的.比如说我们发现某个项目有bug代码,而自己又没有svn的提交权限,那么此时最合适的解决方法就是用diff命令做一个补丁发给项目成员.项目成 ...