microsoft / microsoft/TypeScript

ES `ClassDecoratorContext.name` has incorrect value with static `name`

Open
#62,870 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Decorators Help Wanted
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

### 🔎 Search Terms

ClassDecoratorContext static name

### 🕗 Version & Regression Information

5.0.4-5.9.3

### ⏯ Playground Link

https://tsplay.dev/N7vAow

### 💻 Code

```ts
const decorate = (_: unknown, ctx: ClassDecoratorContext) => {
console.log('decorate(%o)', ctx.name);
};

@decorate
class A {
static get name() {
return 2434;
}
}
```

### 🙁 Actual behavior

`ctx.name` is `2434` (from `A.name`)

### 🙂 Expected behavior

`ctx.name` is `'A'` (actual class name)

### Additional information about the issue

The wrong value comes from the context initializer in the emitted code:

```ts
__esDecorate(
null,
(_classDescriptor = { value: _classThis }),
_classDecorators,
{ kind: 'class', name: _classThis.name, metadata: _metadata },
null,
_classExtraInitializers,
);
```

The context `name` is initialized with `_classThis.name` (which triggers the getter) instead of the actual class name value (literal `"A"` in this case).

## Possible Fix

Currently, the `_classThis.name` fragment comes from `const classNameReference` in `transformClassLike` in `transformers/esDecorators.ts`:

```ts
const classNameReference = factory.createPropertyAccessExpression(renamedClassThis, "name");
```

It should be adjusted to get an actual class name (either literal or computed), possibly like this:

```ts
const classNameReference = node.name ? factory.createStringLiteralFromNode(node.name) :
node.emitNode?.assignedName ?? factory.createStringLiteral("")
```

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in transformers/esDecorators.ts at transformClassLike and inspect how classNameReference is built for the class decorator context. Reproduce the issue with the linked playground, then verify that a class with a static name getter supplies its actual declared name, such as "A", to ctx.name rather than the getter result.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.