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

Type false is not assignable to type this[keyof this] (in 2.1.4) #12878

Closed
newapx opened this issue Dec 13, 2016 · 4 comments
Closed

Type false is not assignable to type this[keyof this] (in 2.1.4) #12878

newapx opened this issue Dec 13, 2016 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@newapx
Copy link

newapx commented Dec 13, 2016

TypeScript Version: 2.1.4

Code

// A *self-contained* demonstration of the problem follows...
export class ClassA {
  public clean() {
    for (let prop in this) {
      if (typeof this[prop] === "boolean")  this[prop] = false;
    }
  }
}

Expected behavior:
Compiled without error

Actual behavior:
Error Type false is not assignable to type this[keyof this]

@dead-claudia
Copy link

Try adding interface BoolMap { [key: string]: boolean; } and change the initial class declaration to class ClassA implements BoolMap. TypeScript doesn't know that ClassA, or subclasses thereof, could even have any dynamic boolean properties, because it can only infer so much. Alternatively, you could use a temporary reference and cast the stored value to {[key: string]: boolean} & this.

(Oh, and you're iterating the prototype chain with that; might be a good idea to guard that with hasOwnProperty.)

@RyanCavanaugh RyanCavanaugh added Question An issue which isn't directly actionable in code Bug A bug in TypeScript and removed Question An issue which isn't directly actionable in code labels Dec 13, 2016
@RyanCavanaugh
Copy link
Member

Should be narrowing this[prop] in the body of the if

@mhegazy
Copy link
Contributor

mhegazy commented Dec 13, 2016

this is a duplicate of #10530. element access expressions are not narrowed.

@mhegazy mhegazy added Duplicate An existing issue was already created and removed Bug A bug in TypeScript labels Dec 13, 2016
@newapx
Copy link
Author

newapx commented Dec 14, 2016

Thank you for the recommendation, but I'm such solutions are not suitable.
I used (<any>this)[prop] = false;

@newapx newapx closed this as completed Dec 14, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants