码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Dynamically initialize class properties using TypeScript decorators

时间:2019-01-28 10:57:42      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:rev   and   config   creat   get   any   abstract   rip   The   

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

标签:rev   and   config   creat   get   any   abstract   rip   The   

原文地址:https://www.cnblogs.com/Answer1215/p/10328266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!