[TypeScript] Reflection and Decorator Metadata

TypeScript allows you to emit decorator metadata which enables more powerful features through reflection. This lesson show you how decorators and reflection fit together and how to configure your own decorators to use reflection.

For now, if we look at the compiled file:

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function addAge(age) {
    return function (targetClass) {
        return (function () {
            function class_1() {
                this.age = age;
                this.name = new targetClass().name;
            }
            return class_1;
        }());
    };
}
var Person = (function () {
    function Person() {
        this.name = "Johnn";
    }
    Person = __decorate([
        addAge(30)
    ], Person);
    return Person;
}());
var john = new Person();
console.log(john); // {name: "Johnn", age: 30}

It decorates addAge to Person class.

Now if we enable "emitDecoratorMetadata" in tsconfig.json:

{
    "compilerOptions": {
        "rootDir": "src",
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "./dist",
        "noEmitOnError": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    },
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}

Compile the files again, now we get:

var Person = (function () {
    function Person() {
        this.name = "Johnn";
    }
    Person = __decorate([
        addAge(30),
        __metadata(‘design:paramtypes‘, [])
    ], Person);
    return Person;
}());

It also add metadata.

Install:

npm install reflect-metadata crypto --save

Index.html:

<script>
    System.config({
        packages: {
            "dist": {
                "defaultExtension": "js",
                "main": "main"
            },
            "rxjs": {
                "defaultExtension": "js"
            }
        },
        map: {
            "lodash": "https://npmcdn.com/[email protected]",
            "rxjs": "node_modules/rxjs",
            "reflect-metadata": "node_modules/reflect-metadata/Reflect.js",
            "crypto": "node_modules/crypto/sha1.js",
        }
    });

    System.import("dist")
</script>

main.ts:

import ‘reflect-metadata‘;

function example(){
    return function(targetClass){
        const types = Reflect.getMetadata(‘design:paramtypes‘, targetClass);
        console.log(types);
        return targetClass
    }
}

@example()
class Person{
    constructor(name: string, age: number){

    }
}
new Person("John", 10);

So in the example() fucntion, we console log out types, it will show:

That means we were able to make it generic, so that any class that comes through into this example decorator, we can look up its types and then use those types to modify or pass into the constructor, and return the class decorated however we want.

时间: 2024-08-05 09:34:04

[TypeScript] Reflection and Decorator Metadata的相关文章

TypeScript 1.5 Beta带来修饰元数据支持

(此文章同时发表在本人微信公众号"dotNET每日精华文章") 今天由于有点小感冒,就不长篇大论了,简单介绍一下和VS 2015 RC一同发布的TypeScript 1.5 Beta的新特性--修饰元数据. 在Build 2015大会上,微软与Visual Studio 2015 RC一同发布了TypeScript 1.5 Beta,通过这个测试版可以了解到TypeScript未来开发进度的情况.微软分别提供了VS2015 RC.VS2013.npm和源代码的安装方式. TypeScr

TypeScript初识

TypeScript 是 JavaScript 的超集,为 JavaScript 的生态增加了类型机制,并最终将代码编译为纯粹的 JavaScript 代码.类型机制很重要吗?最近的一些项目经历让我觉得这真的很重要.当你陷在一个中大型项目中时(Web 应用日趋成为常态),没有类型约束.类型推断,总有种牵一发而动全身的危机和束缚.Immutable.js 和 Angular 2 都在使用 TypeScript 做开发,它们都是体量颇大的项目,所以我决定尝试一下 Typescript.此外我们还可以

反射Reflection

Reflection: 程序集包含模块,而模块包含类型,类型又包含成员.反射则提供了封装程序集.模块和类型的对象.我们可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型.然后,就可以调用类型的方法或访问其字段和属性.简单的来说Reflection就是对Metadata元数据中的一些数据进行简单的操作 Reflection的优点 1,可以更改配置节创建不同的实例 2,使程序更具有动态性 , 3,反射的使用 反射的使用 1 public static IStudent C

在angular2服务中注入服务

http://kittencup.com/javascript/2015/11/11/%E5%9C%A8angular2%E6%9C%8D%E5%8A%A1%E4%B8%AD%E6%B3%A8%E5%85%A5%E6%9C%8D%E5%8A%A1.html 如果你关注我们的文章 Angular2中的依赖注入,你知道DI系统在Angular中是如果运作的,它利用在我们代码上通过注解添加metadata来获取所有关于依赖的信息来解决我们的依赖关系 Angular 2 应用基本上可以用任何语言编写.只

google protobuf 使用示例

1 定义.proto接口文件 package tutorial; message Person { required string name = 1; required int32 id = 2; //unique ID number for this person optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string

如何用vue-cli3脚手架搭建一个基于ts的基础脚手架

目录 准备工作 搭建项目 vue 中 ts 语法 项目代理及 webpack 性能优化 其他 忙里偷闲,整理了一下关于如何借助 vue-cli3 搭建 ts + 装饰器 的脚手架,并如何自定义 webpack 配置,优化. 准备工作 @vue/[email protected] vue 2.6 node v12.13.0 安装 node 安装 node 全局安装 nrm,npm 的镜像源管理工具. npm i nrm -g // 安装 nrm ls // 查看可用源,及当前源,带*的是当前使用的

[Vue +TS] Use Two-Way Binding in Vue Using @Model Decorator with TypeScript

Vue models, v-model, allow us to use two-way data binding, which is useful in some cases such as forms. This lesson shows how to use it by creating a custom checkbox component using the @Model decorator in TypeScript. Checkbox: <template> <div>

[Vue + TS] Use Properties in Vue Components Using @Prop Decorator with TypeScript

With properties we can follow a one-way parent→child flow communication between components. This lesson shows you how you can pass down properties to class based Vue components by using the @Prop decorator from vue-property-decorator. We’ll also see

异常:“System.Reflection.Metadata”已拥有为“System.Collections.Immutable”定义的依赖项

参考动态执行T4模板:https://msdn.microsoft.com/zh-cn/library/bb126579.aspx 我项目是.NET Framework 4.5控制台应用程序写的. 执行用例提示报错:Microsoft.CodeAnalysis未引用,如图截图 项目引用的Microsoft.VisualStudio.TextTemplating.14.0 版本是14.3.25407 在Nuget官网上只找到 Microsoft.CodeAnalysis版本为1.3.0-beta1