zoukankan      html  css  js  c++  java
  • [TypeScript] Understanding Decorators

    Decorators are a feature of TypeScript that are becoming more and more common in many major libraries. This lesson walks you through what decorators are and how to create your own.

    Nomarl way to decorate a object :

    const Person = {name: 'John'};
    
    function addAge(age){
        return function(person){
            return {
                age,
                name: person.name
            }
        }
    }
    
    const john = addAge(30)(Person);
    console.log(john); // {name: "John", age: 30}

    In Typescript, we can enable "experimentaDecorators", which is ES7 feature:

    {
        "compilerOptions": {
            "rootDir": "src",
            "module": "commonjs",
            "target": "es5",
            "noImplicitAny": false,
            "sourceMap": false,
            "outDir": "./dist",
            "noEmitOnError": true,
            "experimentalDecorators": true
        },
        "exclude": [
            "node_modules",
            "typings/main",
            "typings/main.d.ts"
        ]
    }
    function addAge(age){
        return function(targetClass){
            return class{
                age = age;
                name = new targetClass().name;
            }
        }
    }
    
    @addAge(30)
    class Person{
        name = "Johnn";
    }
    
    const john = new Person();
    console.log(john); // {name: "Johnn", age: 30}

    As before we create addAge function as decorator, different from before, it return class, because we want to decorate Person class.

    After the decorator, we will have age prop on the person class.

  • 相关阅读:
    mall
    将UNICODE编码转换为中文
    460. LFU Cache
    957. Prison Cells After N Days
    455. Assign Cookies
    453. Minimum Moves to Equal Array Elements
    434. Number of Segments in a String
    1203. Sort Items by Groups Respecting Dependencies
    641. Design Circular Deque
    441. Arranging Coins
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5573975.html
Copyright © 2011-2022 走看看