0

Whenever I use the !. operator with typescript, my compilation errors dissapear, but I searched a bit, and I am not clear what !. stands for.

For example, finding a div:

let twelveDiv = Array.from(timePickerDivs).find(element => element.innerHTML === '12')

This produces a compilation error that makes sense:

twelveDiv?.innerHTML = '00'; //The left-hand side of an assignment expression may not be an optional property access.ts(2779)

However the !. solves it:

twelveDiv!.innerHTML = '00'; // no compilation error.

Same for a simple class:

class MyAwesomeClass {
  private myNumber: number; //Property 'myNumber' has no initializer and is not definitely assigned in the constructor.ts(2564)
}

In this case both ?. and !. solves the compilation error.

I am familiar with the ?. for the optional properties and arguments in functions/classes, but not that much with the !.. Thanks.

1 Answer 1

2

The ! is the non-null assertion operator. You are telling typescript "i know this looks like it might be null/undefined, but trust me, it's not". This is occasionally needed in cases where typescript can't figure out that your code eliminates the possibility of a null or undefined.

But be aware that like any type assertion, you are telling typescript not to check your work. If you use it, and it actually can be null/undefined, typescript will not alert you to this fact, and you'll get an error at runtime.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.