typescript Decorators TypeError: Function expected

需要启用experimentalDecorators

 

要启用对装饰器的实验性支持,您必须在命令行或tsconfig.json中启用ExperimentalDecorators编译器选项:

command Line:

tsc --target ES5 --experimentalDecorators
 
这个文档说的很有问题,说是要“实验性支持”,而实际上,自ts5之后,启用这个选项实际上是“使用old style decorators/old legacy decorators”
 
TypeScript 5.0 添加了对 ECMAScript 装饰器的支持。它从很久以前(大约 7 年)就支持所谓的 TypeScript 装饰器。这两种类型的装饰器不兼容。编译器选项--experimentalDecorators触发旧式装饰器的使用,它们通常需要--emitDecoratorMetadata才能正常工作。首先,您必须决定要使用哪种类型的装饰器。
 
 
// 在函数调用前执行格式化操作
export const parseDecorator = (
    target: any,
    propertyName: string,
    descriptor: PropertyDescriptor,
): PropertyDescriptor => {
    return {
        ...descriptor,
        value(...args: any[]) {
           ......
        },
    };
}; // 这里,这个方法装饰器会返回一个对象(PropertyDescriptor)而实际需要一个Function,所以就报错了

export interface UserType {
    id: number;
    username: string;
}

class UserService {
    private users: UserType[] = [
        { id: 1, username: 'admin' },
        { id: 2, username: 'pincman' },
    ];

    @parseDecorator
    delete(id: number) {
        ......
        return this;
    }
}
 
 

编译出来

 

var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } // 这个f就是返回的PropertyDescriptor对象,可以看到typeof不能是对象,需要是函数

......

        else if (_ = accept(result)) {

posted @ 2024-03-13 20:03  hrdom  阅读(11)  评论(0编辑  收藏  举报