Property decoder for a specific property type only

I have a property decorator in TypeScript that can only be used for type properties Array. To ensure that this is done, a TypeErroris called at run time if the property type is not Array(using reflects metadata to get information about the property type):

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

    // ...
}

However, I would not consider it too friendly. How can I make it so that the TypeScript compiler allows you to use a specific property decorator only for properties with a specific type?

+4
source share
1 answer

The error you get is due to the lack of a return statement.

- :

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;
  };
}
0

All Articles