Skip to content

Decorators in 4.3.x can't use Object.defineProperty anymore. #44673

Closed
@dannysmc95

Description

@dannysmc95

Bug Report

🔎 Search Terms

  • decorator broken
  • decorator defineProperty
  • decorator Object.defineProperty
  • decorator target issue

🕗 Version & Regression Information

Issue starts in 4.3.x (was previously fine in 4.2.4 and below).

  • This changed between versions 4.2.4 and 4.3.x

⏯ Playground Link

The playground link with this code works fine, so it's not a reliable test, but when using the NPM version of typescript that is where the issue is, see my gist here:
https://gist.github.com/dannysmc95/da689ae30ef6c05e3fb1778a7c8143a8

If you create a basic file with typescript 4.2.4 you will see the file works, if you then install a 4.3.x version (I did a few versions including latest and next) it will say:

Cannot read property 'say' of undefined

💻 Code

function SetValue(): any {
	return (target: Object, propertyKey: string) => {
		Object.defineProperty(target, propertyKey, {
			get: () => {
				return new MyHelper();
			},
		});
	}
}

class MyHelper {
	public say(message: string): void {
		console.log(message);
	}
}

class MyClass {

	@SetValue() public helper!: MyHelper;
}

const instance = new MyClass();
console.log(instance.helper.say('hello'));

🙁 Actual behavior

In versions above 4.2.4 (i.e. 4.3.x) this will throw the error:

TypeError: Cannot read property 'say' of undefined

In versions 2.4.2 and below it will output:

hello
undefined

That is correct.

🙂 Expected behavior

4.3.x should work the same as 4.2.4.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions