calbear47
calbear47

Reputation: 1211

Why does my "If" block fail to act as a typeguard in Typescript?

I'm attempting to write an application with Angular 4.4.6 and Typescript 2.4.2. with the "strictNullChecks" compiler option set to true.

At the top of my component class, I am declaring a property for a form like so:

BasicForm: FormGroup | null;

Then I initialize my form in the OnInit lifecycle hook. Like so:

ngOnInit(){
 this.BasicForm = new FormGroup({
   name : new FormControl('')
  });
}

Problem

When I try to reference my form in a class method, the compiler yells at me, saying "Object is possibly null"...Which confuses me, because I have the reference wrapped in an if block that checks for null.

myMethod(){
    if(this.BasicForm){
      let name = this.BasicForm.get('name').value;
    }
}

To solve this problem, I have to add an non-null assertion operator before accessing my value property.Like so:

myMethod(){
    if(this.BasicForm){
      let name = this.CampgroundForm.get('name')!.value;
    }
}

But I don't like using this...It seems to be counter productive to what TS is trying to achieve.

Why doesn't control flow analysis work here with my typeguard? Is there a better way than adding the non-null assertion operator?

Upvotes: 2

Views: 255

Answers (1)

Sly_cardinal
Sly_cardinal

Reputation: 12993

It looks like the null warning is actually on the result of BasicForm.get().

It might get a little bit ugly to work around:

myMethod(){
    if(this.BasicForm){
        let prop = this.BasicForm.get('name');
        if (prop){
            let name = prop.value;
        }
    }
}

Or you could try adding a helper method that wraps the null check logic:

myMethod(){
    let name = this._formGet('name');
    if(name){
        // do stuff with name
    }
}

_formGet(prop){
    let result;
    if(this.BasicForm){
        let prop = this.BasicForm.get('name');
        if (prop){
            result = prop.value;
        }
    }
    return result;
}

If you're going to be doing that sort of thing a lot, then it might be useful to look into learning about some data types that help you avoid null checks: https://github.com/cbowdon/TsMonad#general-maybe-usage

Upvotes: 2

Related Questions