Skip to content

thisType is not narrowed #44091

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

Closed
Zzzen opened this issue May 14, 2021 · 3 comments
Closed

thisType is not narrowed #44091

Zzzen opened this issue May 14, 2021 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@Zzzen
Copy link
Contributor

Zzzen commented May 14, 2021

Bug Report

πŸ”Ž Search Terms

thisType is not narrowed

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

class Base {
  f() {
    if (this instanceof D1) {
      const s: this = this;
      s.f1();
      this.f1();
    }
  }
}

class D1 {
  f1() {}
}

πŸ™ Actual behavior

compiler throws an error on s.f1(): Property 'f1' does not exist on type 'Base'.

πŸ™‚ Expected behavior

should have no error.

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label May 14, 2021
@RyanCavanaugh
Copy link
Member

instanceof won't allow arbitrary cross-type coercions. If this is the behavior you want, write

class Base {
  f(this: Base | D1) {
    if (this instanceof D1) {
      const s: D1 = this;
      s.f1();
      this.f1();
    }
  }
}

Note that this, the type, does not change meaning depending on the narrowing context it's in

@Zzzen
Copy link
Contributor Author

Zzzen commented May 14, 2021

Thanks! Now I get it. Type is somehow immutable. If this is used as an expression in typeof (which I'm trying to implement in #43898), it should get narrowed. right?

class Base {
  f(this: Base | D1) {
    if (this instanceof D1) {
      const s: typeof this = this;
      s.f1();
    }
  }
}

@Zzzen Zzzen closed this as completed May 14, 2021
@RyanCavanaugh
Copy link
Member

Yeah, typeof x is a "value position" for x and all value logic should apply there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

2 participants