Skip to content

Instantly share code, notes, and snippets.

@dipeshdulal
Last active August 13, 2020 09:46
Show Gist options
  • Save dipeshdulal/3c4f9e221cebcbbf064fc5e83ebfd8ad to your computer and use it in GitHub Desktop.
Save dipeshdulal/3c4f9e221cebcbbf064fc5e83ebfd8ad to your computer and use it in GitHub Desktop.
Decorators in Typescript
const ADecorator = <T extends { new(...args: any[]): {} }>(specs: T) => {
return class extends specs {
A = "test"
constructor(...args: any[]) {
super(...args)
console.log("object constructed")
}
}
}
const SayNameDecorator = (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor
) => {
console.log(Object.keys(target), propertyKey, descriptor)
console.log("from say name decorator.")
}
const Name = (
target: any,
propertyKey: string,
index: number
) => {
console.log(target, propertyKey)
console.log("name here")
}
@ADecorator
class A {
name = "ram"
@SayNameDecorator
sayName(@Name n: string) {
console.log("hello " + this.name + " n: " + n)
}
constructor(name: string) {
console.log("object constructing with name ", name)
this.name = name;
}
}
console.clear()
const a = new A("dipesh");
a.sayName("dips")
@dipeshdulal
Copy link
Author

dipeshdulal commented Aug 13, 2020

OUTPUT LOOKS LIKE

[LOG]: {},  sayName,  0 
[LOG]: name here 
[LOG]: [],  sayName,  { "writable": true, "enumerable": false, "configurable": true } 
[LOG]: from say name decorator. 
[LOG]: object constructing with name ,  dipesh 
[LOG]: object constructed 
[LOG]: hello dipesh n: dips 

Decorators are special king of declaration that can be attached to a class-declaration, methods, parameters. Decorators use the form of @expression, when expression will evaluate a function that will be called at runtime with information about the decorated declaration. These function run:

  • Class Decorator before class construction.
  • Method Decorator before method calling from the class.
  • Parameters Decorators as a function at runtime before (see in logs) as it only adds additional information to the parameters. i.e can only be used to observe that a parameter has been declared on the method. The return value of the parameter decorator is ignored.

Typescript Decorators Handbook: https://www.typescriptlang.org/docs/handbook/decorators.html
Hand book contains what the arguments for the decorator functions will look like and many more information.

reflect-metadata polyfill adds decorator functionality to store the metadata. This polyfill will be implemented later after ECMA Script decorators are accepted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment