Skip to content

Implement decorator metadata proposalΒ #53461

Closed
@justinfagnani

Description

@justinfagnani

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.

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueFix AvailableA PR has been opened for this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions