Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we say decorators in TypeScript? Why not Annotation(like Java) or Attributes(like C#)?

I would like to know the reason why is this feature in TypeScript called Decorator?

Is it just a different name from Annotation or Attribute? Is there any other reason?

What is the difference between a Decorator and an Annotation/Attribute?

like image 870
HamedFathi Avatar asked Apr 30 '16 09:04

HamedFathi


People also ask

Why do we use decorators in TypeScript?

Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript. NOTE Decorators are an experimental feature that may change in future releases.

Is decorator same as annotation?

Annotations are only metadata set on the class using the Reflect Metadata library. Decorator corresponds to a function that is called on the class. Annotations are used for creating an attribute annotations that stores array. Decorator is a function that gets the object that needs to be decorated.

Are decorators still experimental in TypeScript?

Decorators provide a way to annotate or modify a class or class member in TypeScript. However, Decorators are still an experimental feature of the language.

Does angular use TypeScript decorators?

Decorators are a new feature of TypeScript and used throughout the Angular code, but they are nothing to be scared of. With decorators we can configure and customise our classes at design time. They are just functions that can be used to add meta-data, properties or functions to the thing they are attached to.


1 Answers

It's because they do different things.

An annotation adds metadata to a piece of code that can later be read and used by other code. While a decoration decorates some code with some other code.

Take the case of logging.

A logging annotation can be retrieved at runtime by the logger (maybe via reflection) and logging will be generated according to it.

A logging decoration will surround the logged code with a function that logs information.

like image 100
toskv Avatar answered Jan 04 '23 09:01

toskv