简体   繁体   中英

Typescript cannot access property type from typescript decorator. (Target is: {})

I'm currently implementing a dependency injector to use in a VUE js project.

I have created an Inject decorator and I want to be able to access a property type, I had it working yesterday but something has happened and I'm completely lost. I've console logged out JSON.stringify(target) and I receive an empty object which means my decorator is being ran before the class is constructed.

I am using reflect meta data to get the type but it resolves to null as the target is en empty object. It is possible to solve this issue by passing the type as a decorator parameter however that solution isn't as elegant as I would like.

Is there a way to get the decorator to wait until the class has been constructed or is there somewhere I am just going completely wrong? Decorator code is below:

export const Inject = (): any => {
    return (target: any, key: string): any => {
        if (delete target[key]) {
            Object.defineProperty(target, key, {
                get: () => {
                    const type = Reflect.getMetadata('design:type', target, key);
                    return Injector.resolve(type);
                },
            });
        }
    };
};

Decorator annotation is below:

@Inject()
public testService: TestService;

Thanks in advance!

So, after a few days of messing around I FINALLY found an answer as to why this wasn't working and it hurts me as to how blindingly obvious it was. So in the TS config file there is a flag that needs to be set to true in order for decorator meta data to be emitted. The flag is shown below:

"emitDecoratorMetadata": true

Once this was set the code worked exactly like it did before!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM