Field Decorators
You'll learn how decorators can intercept, validate, or transform class field values right when an instance is created.
What Are Field Decorators?
Field decorators apply to class properties (fields), letting you hook into their initialization. Unlike method decorators that wrap behavior, field decorators modify how a field is defined and assigned when you create an object. Think of them as gatekeepers that intercept the field's value at instantiation time—before it's stored on the instance.
How Field Decorators Work
A field decorator receives a context object describing the field, and returns an initializer function. This function runs when the class is instantiated, receiving the intended value and returning what should actually be stored:
function lowercase(value, context) {
return function(initialValue) {
return initialValue.toLowerCase();
};
}
class User {
@lowercase
username = "ALICE";
}
const user = new User();
console.log(user.username); // "alice"
The decorator's returned function transforms "ALICE" to "alice" before it's assigned to username.
Common Use Cases
Validation: Ensure fields meet requirements at instantiation.
function positive(value, context) {
return function(initialValue) {
if (initialValue < 0) throw new Error(`${context.name} must be positive`);
return initialValue;
};
}
class Product {
@positive
price = 99;
}
Default values or normalization: Automatically clean or format data as objects are created, keeping your constructor logic clean and declarative.
The Analogy
Imagine a factory worker who inspects and adjusts each component before it's installed in a product. Field decorators are those workers—they receive raw values and decide what ultimately gets stored.
Key Takeaway: Field decorators transform or validate field values at instantiation by returning an initializer function that intercepts the assignment process.