Why is TypeScript showing an error even with a condition?

I’m encountering an issue with TypeScript (TS2531) and its non-null type checking. I have the following code:

if (this.formGroup.get('inseeActivityCode') !== null) {
    mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode').value; // => TS2531: Object is possibly 'null'.
}

In this code, I’m explicitly checking if inseeActivityCodeControl is not null before accessing its value property. However, TypeScript still gives me the error TS2531: Object is possibly ‘null’ on the inseeActivityCodeControl.value part.

My understanding was that the condition would prevent this error from occurring. Can someone explain why TypeScript is still raising this error and how to resolve it without using the ! assertion operator?
Thanks !

>Solution :

Because static code analysis doesn’t go that far. For TS the result of the get() is sometype | null and that’s what’s used throughout static code analysis. What you can do is assign the result of get(...) to a variable and check that variable against null

let iac = this.formGroup.get('inseeActivityCode');
if (iac !== null) {
  mergedCompanyActivity.inseeActivityCode = iac.value; 
}

Edit

Why does this work for the assignment but not the function call? Because there is no guarantee whatsoever, that two subsequent calls to the same method will return the same (or even a valid) value. It will probably in your case, but the compiler can’t know that. It can only check the method’s signature, which will be function get(key: string) : sometype | null

Imagine a function like

function foo() {
  return Date.now() % 2 === 0 ? "foo" : null;
}

If you now do

if (foo() !== null) { 
  let l = foo().length;
}

there is no guarantee whatsoever, that the second call of foo() will return a string. It might as well return null.

But on the other hand if you do

let f = foo();
if (f !== null) {
  let l = f.length;
}

once the compiler analizes the !== null check it can be sure, that within the condition’s body f is not null. Ie, the type of f has been narrowed down from string | null to string. And that cannot change, unless you reassign the value of f.

Leave a Reply