[TypeScript] Dynamically initialize class properties using TypeScript decorators
2024-09-03 00:24:57
Decorators are a powerful feature of TypeScript that allow for efficient and readable abstractions when used correctly. In this lesson we will look at how we can use decorators to initialize properties of a class to promises that will make GET requests to certain URLs. We will also look at chaining multiple decorators to create powerful and versatile abstractions.
function Get(url) {
return function (target: any, name: string) {
// For future chain or cache on the same 'name'
const hiddenInstanceKey = "_$$" + name + "$$_";
const init = () => {
return fetch(url).then(response => response.json());
}; Object.defineProperty(target, name, {
get: function () {
return init();
},
configurable: true
});
}
} function First(num) {
return function(target: any, name: string) {
const hiddenInstanceKey = "_$$" + name + "$$_";
// access prvious getter on 'name'
const prevInit = Object.getOwnPropertyDescriptor(target, name).get;
const init = () => {
return prevInit()
.then(response => (response as any[]).slice(, num));
}; Object.defineProperty(target, name, {
get: function() {
return this[hiddenInstanceKey] || (this[hiddenInstanceKey] = init());
},
configurable: true
});
}
} class TodoService {
// Decorators runs from bottom to top
@First()
@Get('https://jsonplaceholder.typicode.com/todos')
todos: Promise<any[]>;
} const todoService = new TodoService();
todoService.todos.then(todos => {
console.log(todos);
})
最新文章
- soj杂题
- ime-mode
- Inversions
- iOS AR技术初体验,使用EasyAR示例程序的小白指南
- .NET+Oracle 分页
- mysql远程连接
- 微信小程序 app.json 配置
- winform动态的文字效果
- 适配器模式(Adpater Pattern)
- JavaScript浏览器解析原理
- ORM-面向对象&;关系数据库
- Codeforces Round #521 (Div. 3)
- 修改Linux服务器的ttl值
- jvm 线上命令
- swoole深入学习 1. swoole初始
- rabbitmq级联之shovel插件和exchange.bind
- GitHub C 和 C++ 开源库的清单(含示例代码)
- 线性回归,多项式回归(P2)
- [转载] java的书
- 做更好的自己 ——读《我是IT小小鸟》有感
热门文章
- Maven介绍---POM、Dependency Management、Coordinates
- JS:body元素对象的clientWidth、offsetWidth、scrollWidth、clientLeft、offsetLeft、scrollLeft
- docker从零开始网络(七) 配置daemon和容器
- win上安装Redis并将其设置为服务
- 2014年spark开发者大赛火热进行中!
- Python:文件操作技巧(File operation)(转)
- HDU 2551 竹青遍野(循环,水)
- struts2 action 字段问题
- [POJ 1739] Tony&#39;s Tour
- POJ 2115 C Looooops(Exgcd)