[Typescript] Build Method decorators in Typescript
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的更多相关文章
- [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 ...
- [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 ...
- 深入浅出TypeScript(2)- 用TypeScript创建web项目
前言 在第一篇中,我们简单介绍了TypeScript的一些简单语法,那么如果我们只是简单使用TypeScript开发一个web项目,应该做哪些准备?接下来我们就结合TypeScript和Webpack ...
- [Typescript] Introduction to Generics in Typescript
If Typescript is the first language in which you've encountered generics, the concept can be quite d ...
- 学习TypeScript,笔记一:TypeScript的简介与数据类型
该文章用于督促自己学习TypeScript,作为学笔记进行保存,如果有错误的地方欢迎指正 2019-03-27 16:50:03 一.什么是TypeScript? TypeScript是javasc ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
随机推荐
- elastic学习笔记
要点 不同工具之间版本匹配很重要由点及面,先实践起来再学细节的原理和使用 技术栈 laravel5.5框架+scout组件+elasticsearch6.3.0搜索引擎 辅助 elasticsearc ...
- 新手学python-Day4-进制,数据类型,编码转换,列表
python3中字符串的编码转换 names=b'\xe2\x82\xac20'.decode('utf-8') print(names) names='€20'.encode('utf-8') pr ...
- STM32 SPI 发送第一个数据不成功问题
STM32的标准库,跟HAL库都是很实用的, 在使用SPI库的过程中一定要注意时序的问题. 我在调试SPI过程中,调试了两个IC,都是用HAL库, 第一个IC没出问题,第二个IC出现了第一次发送数据不 ...
- POJ 2296 Map Labeler(2-sat)
POJ 2296 Map Labeler 题目链接 题意: 坐标轴上有N个点.要在每一个点上贴一个正方形,这个正方形的横竖边分别和x,y轴平行,而且要使得点要么在正方形的上面那条边的中点,或者在以下那 ...
- sqlzoo练习答案--SELECT names/zh
name continent Afghanistan Asia Albania Europe Algeria Africa Andorra Europe Angola Africa .... name ...
- web程序定时器
package com.timer; import java.util.Calendar; import java.util.Date; import java.util.Timer; import ...
- iOS-MBProgressHUD使用
在码代码过程中,我们经常用到MBProgressHUD,但我很少实例化使用,一般都是偷个懒直接显示隐藏,这里贴上详解,以便日后有样式要求时使用. 1,MBProgressHUD常用属性和用法Demo ...
- m_Orchestrate learning system---六、善用组件插件的好处是什么
m_Orchestrate learning system---六.善用组件插件的好处是什么 一.总结 一句话总结: 1.面包屑导航是什么? 知道它是什么自然就知道它怎么用了 2.表格里面的栏目能能点 ...
- 搞定ubuntu下环境变量的配置
Ubuntu Linux系统环境变量配置文件: /etc/profile : 在登录时,操作系统定制用户环境时使用的第一个文件 ,此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行. ...
- [jzoj 6087] [GDOI2019模拟2019.3.26] 获取名额 解题报告 (泰勒展开+RMQ+精度)
题目链接: https://jzoj.net/senior/#main/show/6087 题目: 题解: 只需要统计$\prod_{i=l}^r (1-\frac{a_i}{x})$ =$exp(\ ...