Typescript: Why I can't use decorator on property

Created on 27 Oct 2017  路  2Comments  路  Source: microsoft/TypeScript

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.

Most helpful comment

thank you

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Roam-Cooper picture Roam-Cooper  路  3Comments

wmaurer picture wmaurer  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

blendsdk picture blendsdk  路  3Comments