TypeScript
Typescript - Decorators
PHM
2022. 9. 20. 10:52
- 데코레이터는 메타 프로그래밍하는 데 매우 유용하게 사용될 수 있다.
function Logger(constructor: Function) {
console.log('Logging...');
console.log(constructor);
}
@Logger
class Person {
name = 'Max';
constructor() {
console.log('Creating person object...');
}
}
- 데코레이터는 실체화되기 전 클래스가 정의만 돼도 실행된다. 클래스를 실체화할 필요가 없다
데코레이터 팩토리
: 데코레이터 함수를 도출하는데 어떤 대상에 데코레이터를 할당할 때 설정할 수 있도록 해준다.
// EX1
function Logger(logString: string) {
return function(constructor: Function){
console.log(logString);
console.log(constructor);
}
}
@Logger('LOGGING - PERSON')
class Person { ... }
- 팩토리 함수와 함께 실행된다면 데코레이션 함수가 사용하는 값을 커스터마이즈할 수 있다.
- 데이코레이터 팩토리를 사용하면, 데코레이터를 내부에 설정에 사용할 때보다 많은 영향력과 가능성을 펼칠 수 있다.
// EX2
function WithTemplate(template: string, hookId: string){
return function(_: Function){
const hookEl = document.getElementById(hookId);
if(hookEl){
hookEl.innerHTML = template;
}
}
}
@WithTemplate('<h1>My Person Object</h1>','app')
class Person {...}
* _ : 타입스크립트에 시그널이 되는 _ , 인수가 있지만 필요없다.
프로퍼티 데코레이터
function Log(target: any, propertyName: string | Symbol) {
console.log('Property decorator!');
console.log(target, propertyName);
}
class Product {
@Log
title: string;
...
}
- 첫 인수 : 프로퍼티의 타깃, 만들어진 오브젝트의 프로토타입
- 두번째 인수 : 프로퍼티 이름