Skip to content

Array length guardsΒ #54055

@mfulton26

Description

@mfulton26

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions