Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!: (bang colon) notation in Angular

I found !: notation being used in Angular Deprecation docs.

@Input() tpl !: TemplateRef<any>;
@ContentChild(TemplateRef) inlineTemplate !: TemplateRef<any>;

Found the same here as well.

@Input() id !: string;

I'm not sure what is the terminology (or concept behind) for !: notation in Angular. Googling didn't help me much. Tried SymbolHound and Angular Docs for the same, but all in vain.

It'd be helpful if someone could shed some light on it, like how does it function, or share the doc link at the very least.

like image 435
boop_the_snoot Avatar asked Sep 24 '19 05:09

boop_the_snoot


2 Answers

The exclamation mark ! tells, that the field is non-null non-undefined (see Microsoft's TypeScript documentation).

The colon : is just the separator between field name and type.

like image 33
slartidan Avatar answered Oct 18 '22 08:10

slartidan


If you have strictNullChecks on then anything you decorate with @Input will usually complain. For example...

public class MyComponent {

  @Input()
  public myField: string;

  constructor() {}

}

This will lead to TS complaining. This is because myField has not be declared nullable so it should never be set to null or undefined. At the same time, it is not initialized in the constructor, so it will get an initial value of undefined.

Normally, this is fine. We know that Angular will set the value shortly after construction. If we mark the field nullable public myField: string? then we will have to deal with this field may be null errors all over the place when we try and use it.

So, as a compromise, we throw a ! on the field declaration to tell Typescript "I know this looks like it is getting initialized to null/undefined but trust me, I will take care of it".

like image 185
Pace Avatar answered Oct 18 '22 08:10

Pace