-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
Suggestion
I want to be able to check an Array
instance's length
property and then be able to call shift()
, pop()
, etc. and not have to append !
to tell the compiler I have a defined value.
π Search Terms
array length guard shift
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
If I have an Array
instance and I check that its length
property is greater than zero, truthy, etc. then when I call shift()
I don't have to append !
on that call to avoid the returned value being possibly undefined
.
π Motivating Example
let result = 0;
const queue = [1, 2, 3];
if (queue.length) {
const value = queue.shift();
result += value;
}
console.log(result);
Output
"use strict";
let result = 0;
const queue = [1, 2, 3];
if (queue.length) {
const value = queue.shift();
result += value;
}
console.log(result);
Compiler Options
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"target": "ES2017",
"jsx": "react",
"module": "ESNext",
"moduleResolution": "node"
}
}
Playground Link: Provided
π» Use Cases
I could write my while
loop differently but that has other tradeoffs and I want TypeScript to better understand my JavaScript and the runtime structures rather than me code very differently so that TypeScript can understand.
e.g. See #51035 (comment) where instead of a while
loop where its predicate is on length
the let
keyword is used instead. This causes more code, uses a re-assignable variable rather than a single-assignable one (const
), and doesn't read as well IMO.