title: How to type a non-empty array in typescript?
body: <p>I want the typescript compiler to throw an 'Object is possibly 'undefined'' error when trying to directly access any element of the array if the array is not pre-checked for emptiness, so that you always have to check that element for undefined, for example, using an optional chaining</p>
  <p>If it is pre-checked that the array is not empty, then you need to be able to access its elements as usual, without the need to check its elements for undefined</p>
  <p>I need this in order to be sure that the array is not empty, so if it is empty, then access to any of its elements will immediately return undefined then chaining will not continue and there will be no possible errors like cannot read property of undefined</p>
  <p>How do i do this?</p>
  <p>Code example, maybe it will make my question clearer</p>
  <pre><code>interface Element {
    a: {
      aa: string;
      bb: string;
    };
    b: {
      aa: string;
      bb: string;
    };
  }
  
  const element: Element = {
    a: { aa: &quot;aa&quot;, bb: &quot;bb&quot; },
    b: { aa: &quot;aa&quot;, bb: &quot;bb&quot; },
  };
  
  type ElementArray = Element[];
  
  const array: ElementArray = [element, element];
  const emptyArray: ElementArray = [];
  
  const getFirstAWithoutLengthCheck = (array: ElementArray) =&gt; {
    return array[0].a; // i want the typescript compiler to throw an 'Object is possibly 'undefined'' error here
  };
  
  const getFirstAWithLengthCheck = (array: ElementArray) =&gt; {
    if (array.length) {
      return array[0].a; // shouldn't be any errors
    }
    return null;
  };
  
  const getFirstAOptChaining = (array: ElementArray) =&gt; {
    return array[0]?.a; // shouldn't be any errors
  };
  
  // will throw error cannot read property a of undefined, so we need to use
  // optional chaining or length check in this function, but typesript is not requiring it
  console.log(getFirstAWithoutLengthCheck(array)); // aa
  console.log(getFirstAWithoutLengthCheck(emptyArray)); // crash!
  
  // checking array length, access to first element should work as usual, no errors
  console.log(getFirstAWithLengthCheck(array)); // aa
  console.log(getFirstAWithLengthCheck(emptyArray)); // null
  
  // optional chaining, no errors
  console.log(getFirstAOptChaining(array)); // aa
  console.log(getFirstAOptChaining(emptyArray)); // undefined
  </code></pre>