uhyo / better-typescript-lib

Better TypeScript standard library
https://www.npmjs.com/package/better-typescript-lib
Apache License 2.0
423 stars 9 forks source link

Array index signature to optional property #52

Closed narumincho closed 2 weeks ago

narumincho commented 1 month ago
const array: Array<string> = ["a", "aa", "aaa", "aaaa", "aaaaa"];

const handler: ProxyHandler<{ [index in number]: string }> = {
    get(target, prop, receiver) {
        return "a".repeat(Number.parseInt(prop.toString(), 10));
    },
};
const proxyObject: { [index in number]: string } = new Proxy({}, handler);

compilerOptions.noUncheckedIndexedAccess: false (default)

const arrayResult = array[10]; // string
console.log(arrayResult); // undefined (Unexpected. this type is string but this value is undefined)

const proxyObjectResult = proxyObject[10]; // string
console.log(proxyObject[10]); // aaaaaaaaaa (Expected)

compilerOptions.noUncheckedIndexedAccess: true

const arrayResult = array[10]; // string | undefined
console.log(arrayResult); // undefined (Expected)

const proxyObjectResult = proxyObject[10]; // string | undefined (Unexpected. Always expect to string)
console.log(proxyObject[10]); // aaaaaaaaaa

I propose the following changes

  interface Array<T> {
    ...
-  [n: number]: T;
+  [n in number]?: T;
  }

With this change, both types are expected if noUncheckedIndexedAccess is false

uhyo commented 3 weeks ago

Hello, thanks for the suggestion.

However, unfortunately I'm not willing to make this change given that noUncheckedIndexedAccess already covers this.

Approaching this problem from type definition side is imperfect. Also I don't like the idea of suggesting our users to turn off noUncheckedIndexedAccess.

narumincho commented 2 weeks ago

Thanks for your reply. When I tried to change node_modules/@typescript/lib-es5/index.d.ts directly, an error occurred, so it seems that this specification cannot be realized in the first place.

image

Instead of rewriting the type definitions provided by TypeScript, I will implement it by creating and using another type definition. (https://github.com/narumincho/readonly)