属性装饰器仅适用于特定属性类型

Joh*_*isz 5 decorator typescript

我在TypeScript中有一个属性装饰器,只能在类型的属性上使用Array.要强制执行此操作,TypeError如果属性类型不是,则在运行时抛出a Array(使用反射元数据获取属性类型信息):

function ArrayLog(target: any, propertyKey: string) {
    if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
        throw new TypeError();
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,我不会认为这太开心了.我怎么能这样做,以便TypeScript编译器允许在某种类型的属性上使用某个属性装饰器?

Arc*_*ine 0

您收到的错误是由于缺少返回表达式造成的。

尝试一些类似的事情:

export function Decorator(fn:any) {
  return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<Array>) => {
    if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
        throw new TypeError();
    } 
    return descriptor;
  };
}
Run Code Online (Sandbox Code Playgroud)