[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 ...
随机推荐
- 创业笔记-Node.js入门之基于事件驱动的回调
基于事件驱动的回调 这个问题可不好回答(至少对我来说),不过这是Node.js原生的工作方式.它是事件驱动的,这也是它为什么这么快的原因. 你也许会想花点时间读一下Felix Geisendörfer ...
- POJ 2480
可以容易得知,F=sum(p*phi(n/p)).思路就断在这里了... 看过别人的,才知道如下: 由于gcd(i,n*m)=gcd(i,m)*gcd(i,n),所以gcd为积性函数.而积性函数之和为 ...
- java基础之get和post的差别
上篇博文讲到HTTP协议,本篇介绍HTTP请求方法中get和post的差别: 首先,最明显的一点表象上的差别:GET 方式.将请求參数附加在url之后,POST将请求參数附加在请求头的最后 以下具体说 ...
- Spring25大面试题
1.什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台.Spring帮助开发人员攻克了开发中基础性的问题 ...
- sql server执行动态拼接sql(带传参数)和去掉小数点后0的函数
1 exec sp_executesql N'SELECT 2 [Extent2].[Id] AS [Id], 3 [Extent2].[Name] AS [Name], 4 [Extent2].[D ...
- ImageUtils
JavaSE package com.easystructure.utils.system; import java.awt.Color; import java.awt.Font; import j ...
- Dos.ORM使用教程
Dos.C#.Net使用 Dos.ORM(原Hxj.Data)于2009年发布,并发布实体生成工具.在开发过程参考了多个ORM框架,特别是NBear,MySoft.EF.Dapper等.吸取了他们的一 ...
- Java绘图技术基础
public class Demo1 extends JFrame{ MyPanel mp=null; public static void main(String[] args){ Demo1 de ...
- 【原创】websphere部署war包报错
应用程序在Tomcat上运行一切正常,但在websphere上部署时报以下错误:错误 500 处理请求时发生一个错误: /admin/upload.do 消息: WEB-INF/web.xml 详细错 ...
- 浅谈Android和IOS系统的差异
总结:事件响应级别.GPU加速.进程前后台.代码运行速度.内存管理机制. 进程管理机制.内存管理机制.cpu效率.GPU加速.事件响应级别. 1. 渲染机制不同 IOS的UI渲染采用实时优先级, ...