如何实现TypeScript decorator?

TypeScript

飞羽

2020-06-02

TypeScript 1.5现在具有 decorator

有人可以提供一个简单的示例,演示实现 decorator的正确方法并描述可能的有效 decorator签名中的参数的含义吗?

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Function, propertyKey: string | symbol, parameterIndex: number) => void;

此外,在实现 decorator时是否应牢记最佳实践考虑因素?

第4242篇《如何实现TypeScript decorator?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
蛋蛋猿 2020.06.02

在其他答案中我没有看到的一件重要事情:

装饰厂

如果要定制将 decorator应用于声明的方式,则可以编写一个 decorator工厂。 decorator工厂只是一个返回表达式的函数, decorator将在运行时调用该表达式。

// This is a factory, returns one of ClassDecorator,
// PropertyDecorator, MethodDecorator, ParameterDecorator
function Entity(discriminator: string):  {
    return function(target) {
        // this is the decorator, in this case ClassDecorator.
    }
}

@Entity("cust")
export class MyCustomer { ... }

查看TypeScript手册Decorators一章

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android