Skip to content

Narrowing for constant indexed access fails on array getterΒ #58803

Closed as not planned
@grant-d

Description

@grant-d

πŸ”Ž Search Terms

constant indexed access, array

πŸ•— Version & Regression Information

  • This changed between versions 5.4.5 and 5.5.beta
  • This changed in commit or PR

⏯ Playground Link

I could not repro this in playground, due to the lib import

πŸ’» Code

import crypto from 'crypto-js'

const bar = "abc"
const foo: crypto.lib.WordArray = crypto.enc.Utf8.parse(bar) // Returns type: { words: number[], ... }
for (let i = 0; i < foo.words.length; i++) {
  foo.words[i] += 1
//~~~~~~~~~~~~ error TS2532: Object is possibly 'undefined'.

  // Alternatively:
  foo.words[i] = foo.words[i] + 1
//               ~~~~~~~~~~~~ <same error>
}

Adding suitable checks in the loop-body for falsey values does not fix it, eg:

if (foo && foo.words && foo.words[i]) {
 // Same code as above, same error
}

However the following does fix it:

const word = foo.words[i]
if (word) {
  foo.words[i] = word + 1 // OK
}

πŸ™ 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' it

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs More InfoThe issue still hasn't been fully clarified

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions