✊ 필오의 개발일지
Back to Posts
2017년 11월 26일

10/ Decorator

10/ Decorator

타입스크립트 정리 글은 이웅재님의 강의 강의록 을 참고하여 작성하였습니다. (짱짱) 오류가 있다면 언제든지 댓글 부탁드립니다.

요약 아직 잘 이해가 안간다. 😵


1. Decorator 종류

Decorator?


1-1. Decorator 코드 작성 준비

yarn add typeScript -D여기서 Ddev와 같은 명령어다.


2. Decorator

2-1. Class Decorator

2-1-1. Class Decorator Basic

여기서 helloFactory 는 팩토리 패턴

function hello(constructorFn: Function) { console.log(constructorFn); } function helloFactory(show: boolean) { if (show) { return hello; } else { return null; } } // @hello @helloFactory(true) class Person { constructor() { console.log('new Person()'); } } new Person();

2-1-2. Class Decorator Advanced
function addHello(constructorFn: Function) { constructorFn.prototype.hello = function () { console.log('hello'); }; } @addHello class Person { constructor() { console.log('new Person()'); } } const person = new Person(); (<any>person).hello();

2-2. Method Decorator

function editable(canBeEdit: boolean) { return function (target: any, propName: string, description: PropertyDescriptor) { console.log(canBeEdit); console.log(target); console.log(propName); console.log(description); description.writable = canBeEdit; }; } class Person { constructor() { console.log('new Person()'); } @editable(true) hello() { console.log('hello'); } } const person = new Person(); person.hello(); person.hello = function () { console.log('world'); }; person.hello();

2-3. Property Decorator

function writable(canBeWrite: boolean) { return function (target: any, propName: string): any { console.log(canBeWrite); console.log(target); console.log(propName); return { writable: canBeWrite, }; }; } class Person { @writable(false) name: string = 'Mark'; constructor() { console.log('new Person()'); } } const person = new Person(); console.log(person.name); /* undefined */

2-4. Prameter Decorator

function printInfo(target: any, methodName: string, paramIndex: number) { console.log(target); console.log(methodName); console.log(paramIndex); } class Person { private _name: string; private _age: number; constructor(name: string, @printInfo age: number) { this._name = name; this._age = age; } hello(@printInfo message: string) { console.log(message); } } /* Person { hello: [Function] } hello 0 [Function: Person] undefined 1

참고링크

  1. http://poiemaweb.com/es6-class 
  2. https://javarouka.github.io/blog/2016/09/30/decorator-exploring/ 
  3. http://blog-kr.zoyi.co/channel-frontend-decorator/ 
Previous11/ Type Inference
Next9/ itertor

Related

© 2025 Felix