[TypeScript] Understanding Decorators

Source: Internet
Author: User

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

Nomarl to decorate a object:

Const PERSON = {name: ' John '}; function Addage (age) {    returnfunction(person) {        return  {            ,            name:person.name        }    = addage (person); Console.log (John);//{name: "John", age:30} 

In Typescript, we can enable the "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  = = new   Targetclass (). Name; }}} @addAge ( 30 = "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 Pers On class.

After the decorator, we'll have an age of prop on the person class.

[TypeScript] Understanding Decorators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.