Skip to content

thisType is not narrowedΒ #44091

Closed
Closed

Description

@Zzzen

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.

Activity

  1. RyanCavanaugh commented on May 14, 2021

    @RyanCavanaugh
    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

  2. Zzzen commented on May 14, 2021

    @Zzzen
    ContributorAuthor

    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();
        }
      }
    }
  3. RyanCavanaugh commented on May 14, 2021

    @RyanCavanaugh
    Member

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

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions