Front-End/TypeScript

Decorators

JUNNYS 2022. 1. 29. 12:09

Decorators in TypeScript

- Functions that can be used to modify/change/anything different properties/methods(static as well)/accessors/class in the class

- It is different from JavaScript decorators

- Used inside/on classes only

- understanding the order in which decorators are ran are the key to understanding them

- But it is still experimental!! 

- to use decorators, need to set "experimentalDecorators":true, "emitDecoratorMetadata":true

"experimentalDecorators": true 
"emitDecoratorMetadata": true

Decorator example,

class Boat {
  color: string = "red";

  get formattedColor(): string {
    return `This boat color is ${this.color}`;
  }

  @testDecorator
  pilot(): void {
    console.log("swish");
  }
}

function testDecorator(target: any, key: string,  desc: PropertyDescriptor): void {
  console.log("Target", target);
  console.log("Key", key);
}
class Boat {
  color: string = "red";

  get formattedColor(): string {
    return `This boat color is ${this.color}`;
  }

  @logError("Oops boat was sunk in ocean")
  pilot(): void {
    throw new Error();
    console.log("swish");
  }
}

function logError(errorMessage: string) {  //Decorator Factories
  return function (target: any, key: string, desc: PropertyDescriptor): void {
    const method = desc.value;

    desc.value = function () {
      console.log(method);
      try {
        method();
      } catch (error) {
        console.log(errorMessage);
      }
    };
  };
}

new Boat().pilot();

- First argument is the prototype of the object

- Second Argument is the key of the property/method,accessor on the object

- Third argument is the property descriptor (this enables to modify properties/methods of the class)

- Decorators are executed when we define a class (not when an instance is created)

 

 

'Front-End > TypeScript' 카테고리의 다른 글

Decorators  (0) 2022.01.29
Reusable Code (Inheritance vs Composition)  (0) 2022.01.28