> For the complete documentation index, see [llms.txt](https://guide-angular.wishtack.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guide-angular.wishtack.io/typescript/decorateurs/decorateurs-de-propriete.md).

# Décorateurs de Propriété

Le code ci-dessous implémente et utilise un décorateur `ReadOnly` qui surcharge l'implémentation du "setter" de la propriété et déclenche automatiquement une exception en runtime.

`ReadOnly` est une factory qui retourne un décorateur.

Le décorateur prend deux paramètres :

* `target` : la référence de la classe.
* `key` : le nom de la propriété.

```typescript
const ReadOnly = () => {
    
    /* Return the decorator. */
    return (target, key: string) => {
        Object.defineProperty(target, key, {
            set: () => {
                throw new Error(`${target.constructor.name}.${key} is read only`);
            }
        });
    };
    
};

class Customer {
    @ReadOnly() firstName: string;
}

const customer = new Customer();
customer.firstName = 'Foo';
```

Depuis la version 2.0 de TypeScript, il est désormais possible d'indiquer si une propriété est `readonly` avec la syntaxe native suivante :

```typescript
class Customer {
    readonly firstName: string;
}
```

{% hint style="warning" %}
Il faut bien noter la différence entre les deux.

La visibilité readonly n'est analysée que statiquement et peut donner une fausse impression de confiance.

En revanche, le décorateur est exécuté en runtime et il faudra penser à le désactiver en production pour éviter son coût d'exécution.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://guide-angular.wishtack.io/typescript/decorateurs/decorateurs-de-propriete.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
