title: Can I do a type assertion for a variable in Typescript that should be valid for a whole block/function?
body: <p>I have a state variable that is of type <code>null | SOME_TYPE</code>. But some functions expect it to be <code>SOME_TYPE</code> and those functions are 100% sure that the state variable will be <code>SOME_TYPE</code> when they run.</p>
  <p>Can I type cast/assert a variable that will be valid for a whole function scope?</p>
  <p>Example:</p>
  <pre><code>const [myState,setMyState] = useState&lt;null | SOME_TYPE&gt;(null);
  
  function doSomething() {
    // THIS FUNCTION NEEDS myState TO BE SOME_TYPE
    // IT'S 100% GUARANTEED THAT WHEN IT RUNS, myState WILL BE SOME_TYPE
  
    // IT WILL ACCESS MULTIPLE PROPERTIES OF MY STATE
    console.log(myState.someProp as SOME_TYPE);
    console.log(myState.someOther as SOME_TYPE);
    console.log(myState.another as SOME_TYPE);
  }
  </code></pre>
  <p>Instead of multiple and repetitive type casts, can I do a &quot;block&quot; type assertion (without creating a new variable)?</p>
  <p><strong>Example:</strong></p>
  <pre><code>function doSomething() {
  
    // myState as SOME_TYPE
    // THE IDEA IS THAT INSIDE THIS WHOLE BLOCK myState IS CONSIDERED TO BE SOME_TYPE
  
    console.log(myState.someProp);
    console.log(myState.someOther);
    console.log(myState.another);
  }
  </code></pre>
  <p>Is there a syntax or a proposal for that?</p>