Consider the code snippet below written in TypeScript:
const x = [1];
if (x.length !== 1)
throw "error";
x.pop();
if (x.length === 0)
throw "error";
While checking the condition at line if (x.length === 0)
, the compiler raises a strange warning:
This comparison appears to be unintentional because the types '1' and '0' have no overlap.ts(2367)
It seems that after the first check, it always assumes the length is 1 and any modifications to the array do not affect it. The reason behind this behavior is unclear. How can we resolve this issue?
Access the code on Playground using this link: https://www.typescriptlang.org/play/?ssl=9&ssc=15&pln=1&pc=1#code/MYewdgzgLgBAHjAvDA2gRgLoG4CwAofASwDMYAKOAOgBsBTMAcygAsYBCRZNASnxYCcQAdxgAiWv0H9RuAnioAHEArLdZRUhRr0mrTsgAMvPAOFiJUmUA