Repository navigation
Description
Suggestion
Emit type metadata only for decorators that need it.
🔍 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
Note: This might be non-viable under the checklist because it require type-based emit, but type metadata for decorators is already type-based emit, so maybe this is an area where it's ok...
Currently, the emitDecoratorMetadata flag emits metadata for every decorated field, even though many decorators might not need that metadata, which can cause bloat.
The compiler could instead look at some statically available metadata about the decorator itself, so that the decorator can opt-in to type metadata. This opt-in could be part of the type of the decorator function, ie you have to cast the decorator to a type that signals the decorator needs metadata:
const property = (options): ClassAccessorDecoratorWithMetadata => (target, context) => { /* ... */ };📃 Motivating Example
Any program that uses a combination of decorators that need type metadata and those that don't.
💻 Use Cases
Workarounds are difficult here. Maybe developers can create separate projects and try to isolate those that require type metadata, but that might not always be possible - there might be single files that uses both decorators that require type-metadata and decorators that don't.
Activity
thetutlage commentedon Jul 1, 2023
Another use case for this will be co-locating legacy and stage 3 decorators inside a single codebase.
Even with TypeScript 5.2 (with decorators metadata) implemented. Creating a sane Dependency injection system is hard, because the new metadata API does not provide method parameters or constructor parameters and their types.
Given the following example, using the Stage 3 decorators + new metadata API, there is no way for the
@injectdecorator to know that the class constructor has one param and its value is of typeUserService.However, it is possible with legacy decorators.
Coming back, if we can allow legacy + Stage 3 decorators to co-exist, then I can use Stage 3 decorators for most of the use cases and legacy one's for DI and other specific use cases