2

I am working on angular project , while editing the component.ts file example given by my teacher . a line of code appears .

@Input() public searchType!: string;

It is inside the component typescript OnInit() function , I have no idea what the symbol ! means in this line of code and what is the effcts it brings . As far as I know , it means not equals as an operator in language like php , java , but what does it mean when initializing a variable for typescript ?

AkiZukiLenn
  • 337
  • 3
  • 14
  • I looked at the title , it seems that it should answer my question , when I google it , the link you shown is not on the result first page oddly , and when I post this question , the "similar question check" function didn't tell me , should I instantly delete this question , as it seems this violate the laws .... – AkiZukiLenn Feb 27 '22 at 19:16
  • Well technically it's a different operator when dereferencing than declaring a field. But all you need to know is that it's called the "non-null assertion operator" and you can find all the right docs. – windowsill Feb 27 '22 at 19:20

1 Answers1

6

! - aka TypeScript's "non-null assertion operator", is a way to tell typescript that you know for sure the value of a property is neither null nor undefined.

Note that this is potentially dangerous, since if the value does end up being null or undefined, it could result in unwanted behavior. As you can infer, this is a way to "silence" typescript, and therefor should only be used if you are sure that it is correct for your use-case.

This is different to JavaScript's ?, aka "optional-chaining operator", which is a way of saying that the value might be undefined, and that in such a case, it should simply return an undefined.

tomleb
  • 2,409
  • 2
  • 9
  • 24