https://stackoverflow.com/questions/29775830/how-to-implement-a-typescript-decorator




General Points

  • Decorators are called when the class is declared—not when an object is instantiated.
  • Multiple decorators can be defined on the same Class/Property/Method/Parameter.
  • Decorators are not allowed on constructors.
























1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function editable(isEdit:boolean){
    return function(target:any, propName:string,description:PropertyDescriptor){
        console.log(target);
        console.log('propName:'+propName);
        console.log(description);
 
        target.heyjude = 'heyjude';
    }
}
 
 
class Person{
    constructor(){
        console.log('new Person():');
    }
 
    @editable(true)
    hello(){
        console.log('hello');
    }
}
 
const person = new Person();
person.hello();
console.log(person.heyjude);
 
 
// Person {}
// propName:hello
// { value: [Function: hello],
//     writable: true,
//         enumerable: false,
//     configurable: true }
// new Person():
// heyjude
 
cs





  • target: The prototype of the class (Object).
  • propertyKey: The name of the method (string | symbol).
  • descriptor: A TypedPropertyDescriptor — If you're unfamiliar with a descriptor's keys, I would recommend reading about it in this documentation on Object.defineProperty (it's the third parameter).
※decorator는 선언과 동시에 콜되기 때문에, const person = new Person();초기화되지 않아도 class Person{...}만으로 실행된다.




































'frameworks > typescript' 카테고리의 다른 글

tsconfig 컴파일 옵션 정리  (0) 2019.04.05
interface와 class의 상속관계 증명  (0) 2019.02.07
[typescript]iterator  (0) 2018.12.11
[typescript]generic(+additional:string literal type)  (0) 2018.12.07
[typescript]class  (0) 2018.12.07

+ Recent posts