title: Keep track of state in class instance
body: <p>I want to create a class that has some internal state (could be loading, error or success). I also want to have some methods on the class that can check on the state of this class.</p>
  
  <p>Ideal API:</p>
  
  <pre><code>function f(x: LoadingError&lt;number&gt;) {
    if (x.isLoading()) {
    } else if (x.isError()) {
    } else {
      (x.data); // TypeScript knows x.data is of type `number`
    }
  }
  </code></pre>
  
  <p>The main thing that I am struggling with is creating the <code>isLoading</code> and <code>isError</code> methods such that TypeScript can understand them.</p>
  
  <p>I tried to write some user defined type guards on the actual class structure ("<code>" this is { ... }</code>"):</p>
  
  <pre><code>class Foo {
    public value: string | null;
    public hasValue(): this is { value: string } {
      return this.value !== null;
    }
  }
  
  const foo = new Foo();
  if (foo.hasValue()) {
    // OK
    foo.value.toString();
  } else {
    (foo.value); // TypeScript does NOT understand that this can only be null
  }
  </code></pre>
  
  <p>However, that doesn't work since TypeScript "forgets" about the state of the class instance on the <code>else</code> clause.</p>
  
  <p>One of my hard requirements is using a <strong>class</strong> for this, since I don't want to have <code>isLoading(instance)</code> or <code>isError(instance)</code> methods but rather <code>instance.isLoading()</code> and <code>instance.isError()</code>.</p>