title: How to tell typescript that a variable is now not null?
body: <p>(I'm an old-school C/C++ guy just learning typescript.)</p>
  
  <p>I have some code like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>class myClass {
    v: string | null = null
  
    setVtoNonNull() { this.v = "hi" }
  
    method() {
      if (!this.v)
        this.setVtoNonNull()
      // now at this point v is definitely not null
      // how do I tell typescript that?
      const s: string = this.v // &lt;&lt;&lt;&lt; typescript gives error here
    }
  }
  </code></pre>
  
  <p>In <code>method</code>, how do I tell typescript that after the <code>setVtoNonNull()</code> call, local variable <code>v</code> is not null? I know I can use <code>v!</code> wherever I use <code>v</code> after it's set (but that's annoying if I use <code>v</code> a lot), or I could do this horrible hack:</p>
  
  <pre><code>   v = v!
  </code></pre>
  
  <p>but that would cost cycles at runtime just for compile-time cleanliness. Is there a compiler directive or something I can use?</p>