0

I've just upgraded from Angular 7.1.4 to 8.2.0, Typescript 3.1.6 to 3.5.3, RxJS

Before the upgrade, TS correctly identified that this array item is not undefined, but now I'm getting this frustrating compilation error. (note, I'm using lo-dash below, but the same error occurs if I use if (autoCorrectionData[action.algorithmId] !== undefined) {

src/app/state/edit/edit.reducer.ts(417,29): error TS2532: Object is possibly 'undefined'.

How can I get TypeScript to recognize that the Object IS defined after I check using the if condition?

*edit* This might have something to do with recent changes to NGRX Dictionaries, but I'm not sure why. Dictionary values can now be undefined.

enter image description here

HankScorpio
  • 3,612
  • 15
  • 27
  • It appears that TS 3.5 compiler need to specify the type of an object or make it explicit any. Try following: `const acd = autoCorrectionData as any` OR `const acd = autoCorrectionData as Array` [or of your type] and then change your code as per `acd`. – user2216584 Aug 01 '19 at 03:08
  • In this case `autoCorrectionData` is already typed as `Dictionary` – HankScorpio Aug 01 '19 at 17:19
  • I suppose what I *could* do is use the non-null assertion operator `!` to manually assert that the data is defined. That shouldn't be necessary though. TS was smart enough to figure this out before, so there must be a way. – HankScorpio Aug 01 '19 at 17:25

1 Answers1

0

This change to the code removed the error, but... why is this necessary?

A co-worker suggested this might have something to do with recent changes to the rxjs Dictionary, which specifies that values can now be undefined, but this seems really silly.

enter image description here

HankScorpio
  • 3,612
  • 15
  • 27
  • For some reason, TypeScript only supports Type narrowing on a root object. When it has to de-reference an object (index, property, method, etc...), type narrowing (like recognizing that `undefined` has been eliminated from a union), no longer works and it assumes the full union. So, refactoring a complex reference into a simple, local variable for `null` or `undefined` checks, or any Type guard, is quite common. – Zarepheth Aug 26 '19 at 15:20