[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 ...
随机推荐
- Swoole WebSoctet 使用 zlib 压缩之 PHP 与 pako.js
一些理论知识 先说一下deflate算法吧,deflate是zip压缩文件的默认算法, 其实deflate现在不光用在zip文件中, 在7z, xz等其他的压缩文件中都用, 实际上deflate只是一 ...
- python--(爬虫-re模块)
python--(爬虫-re模块) re模块四大核心功能: 1.findall 查找所有,返回list import re lst = re.findall("m", " ...
- zoj 3471 Most Powerful(状压dp+Tsp问题+连续性问题)
上来直接一波敲键盘,直接套Tsp问题的代码 然后WA 发现貌似这道题没有连续性. Tsp问题是一条路径,一个点到另一个点,多了一个限制,所以就需要加多一维 而这道题没有限制,也就是说那一维不需要加,我 ...
- C# 上位机的USB设备拔插检测
我们做USB通信时,通信成功后,往往要检测USB设备的拔插状态,这里就USB拔插进行一下说明. 参考:https://www.imooc.com/article/17438 先说明一下,我这里只是用C ...
- Docker可视化管理工具对比(DockerUI、Shipyard、Rancher、Portainer)
1.前言 谈及docker,避免不了需要熟练的记住好多命令及其用法,对于熟悉shell.技术开发人员而言,还是可以接受的,熟练之后,命令行毕竟是很方便的,便于操作及脚本化.但对于命令行过敏.非技术人员 ...
- 楼宇自控-BA系统流程总图
总结一下过程中的节点和技能,希望能对其他人有所帮助
- 楼宇自控-RS232\RS485\RS422
1.rs-232-c rs-232-c是美国电子工业协会eia(electronic industry association)制定的一种串行物理接口标准.rs是英文"推荐标准"的 ...
- 自己动手写shell命令之more
unix下more命令的简单实现: #include <stdio.h> #define PAGELEN 24 #define LINELEN 512 int do_more(FILE * ...
- Android多媒体学习六:利用Service实现背景音乐的播放
Android同意我们使用Service组件来完毕后台任务.这些任务的同意不会影响到用户其它的交互. 1.Activity类 [java] view plaincopy package demo.ca ...
- android选择图片或拍照图片上传到server(包含上传參数)
在9ria论坛看到的.还没測试,先Mark与大家分享一下. 近期要搞一个项目,须要上传相冊和拍照的图片.不负所望,最终完毕了! 只是须要说明一下,事实上网上非常多教程拍照的图片.都是缩略图不是非常清晰 ...