-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Narrowing for constant indexed access fails on array getter #58803
Comments
You can often import npm packages in the playground just fine. It's capable of fetching their types. I don't see any error here with the nightly version: TS playground. This would indeed show the difference in the behavior: This, in turn, looks like a correctness improvement. |
If this is just an array, I don't see why you need |
@RyanCavanaugh yes I am aware of that, but I was unable to find a repro without the package. @Andarist I think you nailed it - thanks so much, that must be the issue. Not sure what the action is here, I am closing but please re-open as necessary. |
@RyanCavanaugh here is a minimal repro in TS Playground (based on @Andarist example) Including code here too for ease of tracking: // @noUncheckedIndexedAccess: true
interface Foo { words: number[] }
const foo: Foo = { words: [1, 2, 3] }
for (let i = 0; i < foo.words.length; i++) {
foo.words[i] += 1 // Alternative 1) Same error as below
foo.words[i] = foo.words[i] + 1 // Alternative 2) Same error as below
// Alternative 3) Explicit falsey check still fails
if (foo.words[i]) {
foo.words[i] = foo.words[i] + 1
// ^Object is possibly 'undefined'.(2532)^
}
} |
The problem here is that
|
Oh, this just never works for variables that are reassigned: function f1(obj: Record<string, unknown>) {
let key: string = "";
if (typeof obj[key] === "string") {
obj[key].toUpperCase();
}
key = ""; // toggle to see the error to go away and come back
} This is kinda spooky to see an error pop up on a previous line that seemingly has no real correlation with the line that just got added. |
Possibly related |
π Search Terms
constant indexed access, array
π Version & Regression Information
5.4.5
and5.5.beta
β― Playground Link
I could not repro this in playground, due to the lib import
π» Code
Adding suitable checks in the loop-body for falsey values does not fix it, eg:
However the following does fix it:
π Actual behavior
error TS2532: Object is possibly 'undefined'.
π Expected behavior
No error - this type-checked fine previously
Additional information about the issue
This issue is new since the new
Control Flow Narrowing for Constant Indexed Accesses
feature. Rolling back to the previous typescript version 'fixes' itThe text was updated successfully, but these errors were encountered: