QUESTIONS: When I use decorator which is defined by myself on property and typescript throw an error:Unable to resolve signature of property decorator when called as an expression.
Typescript version:2.5.3 Vue:2.5.2
Code
@AutoWired
private userService: IUserService;
const AutoWired = (target, name, descriptor) => {
import(ioc[name]).then((service) => {
descriptor.value = new service();
return descriptor;
});
return descriptor;
};
Expected behavior:
no error
Actual behavior:
Unable to resolve signature of property decorator when called as an expression.
That is because the decorator's third parameter, the property descriptor, is only available when targeting members on the class prototype like methods or properties defined in terms of accessors . A decorator for a regular property only takes a target and a key.
Note you can create a decorator that works for both the 2 and 3 argument scenarios by making the third parameter optional.
I take it you are trying to set up a property that will _eventually_ be given the value of the asynchronously resolved service but that will start out undefined. If so, you want something like
export const AutoWired = <T>(target: T, key: keyof T) => {
let service: UserService;
Object.defineProperty(target, key, {
get: () => service,
set: value => service = value,
enumerable: true
});
import(ioc[key]).then(Service => {
service = new Service();
});
};
export class A {
@AutoWired userService: UserService;
}
thank you
Most helpful comment
thank you