typescript decorator
Estimated reading time: 1 minutedecorator
In TypeScript, a decorator is a function that takes in a target object (such as a class, method, or property) and returns a new object with the same structure, but possibly enhanced with additional features. Decorators are a language feature that allows you to annotate and modify classes and class members at design time.
@
represent decorator @test
method decorator
function auth(){
return function (target: any, key: any, descriptor: PropertyDescriptor){
let fn = descriptor.value
let isAuth: boolean = false
if (isAuth){
descriptor.value = (...args: any) => {
let f = fn(...args)
return f
}
} else {
descriptor.value = () => {
return "login required"
}
}
}
}
class User{
@auth()
profile(name: string){
return("profile: " + name)
}
}
let user: any = new User()
console.log(user.profile('kamal'))
resources
- decorator official
- gist remojansen
- class decorator
- decorator youtube - Ben Awad ***
- decorator codeburst ***