Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive in "variable is never read" when using object.defineProperty #40440

Closed
mastrzyz opened this issue Sep 8, 2020 · 2 comments
Closed
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@mastrzyz
Copy link

mastrzyz commented Sep 8, 2020

I was originally looking at the migration guide on how to fix accessors overriding properties in TS -> #33509

Part of that guidance was using object.defineProperty and defining the getter/setter over there but hit a strange compiler error.

TypeScript Version: 3.8.3

Search Terms:

  • object define property false positive
  • unread variable define property
    Code
export class Foo {
  private _value: string | undefined;

  constructor() {
    Object.defineProperty(this, "value", {
      get() {
        return this._value;
      }
    });
  }
}

Expected behavior:

No compiler errors as I am defining a setter for the _value so the value is being read somewhere

Actual behavior:

'_value' is declared but its value is never read.

If I remove _value I get

Property '_value' does not exist on type 'Foo'. Did you mean 'value'?

Playground Link:
https://www.typescriptlang.org/play?ts=3.8.3#code/KYDwDg9gTgLgBAYwDYEMDOa4DEITgbwFgAoOOMKASwDcUZg4B9WpAV2AC440YqA7AOZwAPnFZ8AJsABmlPsAkBuEiTIIIfHlFYIY0ABQBKAqrJwA8gCMAVsF0A6KbPkAFKBDDBYAT30wAFpRoADRwAEQs7GGhRKRmZALAMEYmcfFkUEmsUHxwAUH2zChswMppZgC+pmQVhmU1JBVAA

Related Issues:

@j-oliveras
Copy link
Contributor

Typescript don't understand that this in the getter definition will be the class. As a workaround, define the type of this inside the getter:

export class Foo {
  private _value: string | undefined;

  constructor() {
    Object.defineProperty(this, "value", {
      get(this: Foo) {
        return this._value;
      }
    });
  }
}

Playground

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Sep 9, 2020
@RyanCavanaugh
Copy link
Member

👆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants