TypeScript Reference ยท Classes, Enums and Decorators
TypeScript field decorators
Reference for standard TypeScript field decorators: the undefined first argument, returning an initializer function to transform values, typing and why they cannot see the field.
A field decorator is applied to a class property declaration. Its first argument is always undefined, because a field has no function at definition time. What it can do is return an initializer function, which receives the field's initial value and returns the value that is stored instead.
That makes field decorators good for defaults and normalization at construction time, but not for intercepting later writes. For that, use an auto-accessor.
function upper(_: undefined, context: ClassFieldDecoratorContext) { return (initial: string) => initial.toUpperCase(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type FieldDecorator<This, V> = ( value: undefined, context: ClassFieldDecoratorContext<This, V>, ) => ((this: This, initial: V) => V) | void;
| Name | Description |
|---|---|
value |
Always undefined. |
context |
kind: "field", name, static, private, access with get/set, addInitializer, metadata. |
Returns: void, or a function that maps the initial value to the stored value.
Edge cases: the initializer runs once per instance (once per class for static fields), in field order, with this as the new instance.
Usage notes
- The initializer only affects the starting value. Later assignments (
u.code = "later") bypass it, as the first example shows. - Use
context.access.get/setto read or write the field from another place, andcontext.addInitializerto run code right after the field is set up. - Fields are initialized after
super()returns in derived classes, so a decorator cannot depend on a value set by the parent constructor body. - The field's declared type and the decorator's
Vmust agree; mismatches are compile errors. useDefineForClassFieldsis on for modern targets, which is the semantics decorators are designed for.