I have a property decorator in TypeScript that is only usable on properties of type Array
. To enforce this, a TypeError
is thrown at runtime if the property type is not Array
(using reflect metadata to get property type information):
function ArrayLog(target: any, propertyKey: string) {
if (Reflect.getMetadata("design:type", target, propertyKey) !== Array) {
throw new TypeError();
}
// ...
}
However, I wouldn't consider this too dev-friendly. How could I make it so that the TypeScript compiler allows using a certain property decorator only on properties with a certain type?
The error you are getting is due to the return expression missing.
Try something along the lines:
There is a little trick to achieve this:
Or even better (Just found in https://stackoverflow.com/a/47425850/274473):
Unfortunately this only works for public properties, not for private or protected properties...