Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript decorator for function, not method. Possible?

I'm trying to add a custom TypeScript decorator in a function which is not included in a class and it seems that the compiler is complaining no matter what I do.

Any thoughts? Is it possible?

like image 224
Nick Tsitlakidis Avatar asked May 30 '16 06:05

Nick Tsitlakidis


People also ask

What is decorator function in TypeScript?

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression , where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

Can a decorator be a method?

Decorators can be implemented in a number of different ways. One useful use-case for decorators involves using them with methods defined in a class. Decorating methods in the classes we create can extend the functionality of the defined method.

Can I use decorators in TypeScript?

In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.

Is decorator is a function?

By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.


1 Answers

add a custom TypeScript decorator in a function

Not to a raw function. The main issue is dealing with hoisting of functions. Any attempt to wrap a function in another function breaks the hoist.

Support Targets

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.

Docs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators

like image 82
basarat Avatar answered Oct 18 '22 21:10

basarat