Last active
August 13, 2020 09:46
-
-
Save dipeshdulal/3c4f9e221cebcbbf064fc5e83ebfd8ad to your computer and use it in GitHub Desktop.
Decorators in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT LOOKS LIKE
Decorators are special king of declaration that can be attached to a class-declaration, methods, parameters. Decorators use the form of
@expression
, whenexpression
will evaluate a function that will be called at runtime with information about the decorated declaration. These function run: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.