uhyo/ts-array-length

the provided API functions do not appear to be type-safe

Opened this issue · 1 comments

The following example causes TypeError:

// const arr: string[]
const arr = ['a'];

if (hasLength(arr, 1)) {
  // README claims: arr: readonly [string]
  // but actually: arr: string[] & readonly [string]
  arr.shift();
  const str: string = arr[0];

  // TypeError: Cannot read properties of undefined (reading 'length')
  console.log(str.length);
}

with tsconfig.json:

{
  "compilerOptions": {
    // ...
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "noUncheckedIndexedAccess": true,
    // ...
  }
}
>npx tsc --version
Version 4.9.5

>node --version
v18.14.2
uhyo commented

Thanks, yes TypeScript doesn't allow weakening types through user-defined type guards, which prevents our util from prohibiting array mutation.

I believe there is no way to ensuring given readonly array is never mutated, given that mutable array types are assignable to readonly array types. This makes perfect type safety impossible.

But I have an idea for a bit of improvement, I'll try it later.