1

I create a component in angular 6 with sample on how to implement decorators. So, I create a custom decorator called @Course and set a value there, named Angular 6. Now, how to get that value in my component's constructor?

I want to log the "Angular 6" value to my constructor. How's that possible?

Here is my code. Work's fine. I've got the value. But got an error in command line

ERROR in src/app/components/decorators/decorators.component.ts(19,22): error TS2339: Property 'course' does not exist on type 'DecoratorsComponent'.

import { Component, OnInit } from '@angular/core';

function Course(target) {
  Object.defineProperty(target.prototype, 'course', {
    value: () => "Angular 6"
  })
}

@Course
@Component({
  selector: 'app-decorators',
  templateUrl: './decorators.component.html',
  styleUrls: ['./decorators.component.scss']
})
export class DecoratorsComponent implements OnInit {

  constructor() {
    console.log(this.course());
  }

  ngOnInit() {
  }
}
Codeblooded Saiyan
  • 1,457
  • 4
  • 28
  • 54
  • I think you misunderstood what decorators are and how they work in conjunction with the type(s) they decorated on. Can you provide a link to the tutorial you mentioned? – Igor Aug 23 '18 at 17:12
  • How do I implement decorators the right way? I don't have tutorial link – Codeblooded Saiyan Aug 23 '18 at 17:26
  • Possible duplicate of [How to implement a typescript decorator?](https://stackoverflow.com/questions/29775830/how-to-implement-a-typescript-decorator) – Igor Aug 23 '18 at 17:32

2 Answers2

0

target.prototype.course = () => 'Angular 6';

menelai
  • 11
  • 3
0

You just need to tell TypeScript compilier about dynamically added property. The simplest way:

@Course
// ...
export class DecoratorsComponent implements OnInit {
    // ... 
    [key: string]: any;
}

Alternatively, you read the dynamic property as "array item":

constructor() {

    const courseProp = this['course'];

    if (courseProp) {
        console.log(courseProp());
    }
}

NOTE: it is good practice to check existence of the property, because decorator may be removed.

IStranger
  • 1,868
  • 15
  • 23
  • While this works, it feels like a major failing of TypeScript. The first answer allows anything, the second means there is no compile-time checking (or IntelliSense). Is there really no better way? – cjbarth Feb 17 '19 at 17:17