Description
Suggestion
Implement decorator metadata
π Search Terms
decorator metadata
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Now that decorators are shipping in TypeScript and decorator metadata has reached consensus on the approach needed for it to proceed to Stage 3, it seems like it may be time to implement metadata.
π Motivating Example
There are examples on the metadata repo, but a quick one is storing information about a class member to be used by the class's base class. Here we generate a custom element's observedAttributes
by decorating fields:
// Library code:
const attributes = new WeakMap<typeof BaseElement, Array<string>>();
class BaseElement {
static get observedAttributes() {
// real code would get attributes from super-classes too
return attributes.get(this[Symbol.metadata]);
}
}
const attribute = (_, {name, metadata}) => {
attributes.set(metadata, (attributes.get(metadata) ?? []).push(name));
}
// Usage:
class MyElement extends BaseElement {
@attribute
foo?: string;
}
π» Use Cases
There are many use cases in the various decorators repositories and documents. Generally any time that some other API besides the decorated one needs information about the decorated items, you will need metadata.
It's worth noting that many libraries can't use decorators until metadata is implemented.