[TypeScript] Dynamically initialize class properties using TypeScript decorators
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Dynamically initialize class properties using TypeScript decorators相关的知识,希望对你有一定的参考价值。
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(0, num)); }; Object.defineProperty(target, name, { get: function() { return this[hiddenInstanceKey] || (this[hiddenInstanceKey] = init()); }, configurable: true }); } } class TodoService { // Decorators runs from bottom to top @First(3) @Get(‘https://jsonplaceholder.typicode.com/todos‘) todos: Promise<any[]>; } const todoService = new TodoService(); todoService.todos.then(todos => { console.log(todos); })
以上是关于[TypeScript] Dynamically initialize class properties using TypeScript decorators的主要内容,如果未能解决你的问题,请参考以下文章
Dynamically allocated memory 动态分配内存mallocMemory leaks 内存泄漏
调整高度Tags Dynamically Generated By ng-if Directive
RNN,LSTM,SRNN,Long Short-Term Memory as a Dynamically Computed Element-wise Weighted Sum
论文解读-Long Short-Term Memory as a Dynamically Computed Element-wise Weighted Sum