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开发环境

    package hadoopDemo; import java.io.IOException; import java.net.URI; import java.net.URISyntaxExcept ...

  2. Python学习笔记(7)字典

    2019-03-07 字典(dict): (1)字典用大括号({})定义,字典由多个键及其对应的值组合而成,每一对键值组合称为项. (2)字典的键唯一,但是值可以是任何(不可变的)数据类型(整型,字符 ...

  3. 新手学python-Day2-变量和循环判断

    第二天作业: 初探三级菜单,凭现有知识,注意变量可以不声明,但要提前赋值! 此处shuru = '' 可以不写,因为第7行被赋值了,如果只调用shuru不赋值就会报错 shuru = '' sheng ...

  4. snprintf

    snprintf(),函数原型为int snprintf(char *str, size_t size, const char *format, ...).   将可变参数 “…” 按照format的 ...

  5. Vue 实现前进刷新,后退不刷新的效果

    需求一: 在一个列表页中,第一次进入的时候,请求获取数据.点击某个列表项,跳到详情页,再从详情页后退回到列表页时,不刷新.也就是说从其他页面进到列表页,需要刷新获取数据,从详情页返回到列表页时不要刷新 ...

  6. 高级函数-decode

    decode(字段或计算表达式,           条件值1,结果值1,           条件值2,结果值2[,默认值]           )      if(字段或计算表达式 == 条件值1 ...

  7. 洛谷—— P1260 工程规划

    https://www.luogu.org/problem/show?pid=1260 题目描述 造一幢大楼是一项艰巨的工程,它是由n个子任务构成的,给它们分别编号1,2,…,n(5≤n≤1000). ...

  8. POJ——T2352 Stars

    http://poj.org/problem?id=2352 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 46592   ...

  9. unity3d 延迟运行脚本语句

    在Unity3D中.有yield语句它负责延迟操作,yield return WaitForSeconds(3.0); //等待 3 秒 查看unity3d脚本手冊,使用方法须要在对应的格式. 以下代 ...

  10. tableau desktop(三)--构建数据视图(二)

    前段时间忙于工作的事情,好久没有来记录一点东西了,今天利用周末做点记录吧,近期因为工作的原因,也有两三周没实用tableau了.今天继续上一篇构建数据试图(二). 3.7 參考线和參考区间 參考线通经 ...