Why Typescript allow me to use any array element without forcing me to check if the index is valid?
Here is what I mean
function return_array(p:boolean):string[]{
return (p) ? ['s'] : [];
}
const arr = return_array(false);
arr[30].toUpperCase();
This will obviously lead me to an error
Cannot read property 'toUpperCase' of undefined
Is this by design or am I missing something?
Edit
The real function is something like:
function return_array(p:boolean):string[]{
// querying the db, it can return an empty array.
return db_response;
}
arr[30]first before attempting to chain anything to it. Optional chaining operator and/or null coalescing operator are your best friends, e.g.a[30]?.toUpperCase();[string]