2

I got error on:

 user = new BehaviorSubject<User>(null);

but:

user = new BehaviorSubject<User>(null!);

was not an error. What is the the use of null! in this context?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sameraze agvvl
  • 397
  • 4
  • 11
  • `!` is the non-null assertion operator, so that's definitely a mistake. – jonrsharpe Apr 14 '22 at 11:11
  • If you want your behavior subject to allow both `User`s and `null`s, then the right way to do it is `user = new BehaviorSubject(null)` – Nicholas Tower Apr 14 '22 at 11:12
  • 1
    I'm reopening this because `null!` is actually a fairly common idiom for pretending that you have a value of type `never`, which is assignable to every type. At runtime the value will be `null`, so you are 100% lying to the compiler. But sometimes it's useful to do this. I need to collect use cases. – jcalz Apr 14 '22 at 13:19
  • Does this answer your question? [In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) – Vega Apr 14 '22 at 13:30
  • Or https://stackoverflow.com/q/58592161/5468463 – Vega Apr 14 '22 at 13:30
  • This is a duplicate of https://stackoverflow.com/questions/58592161/what-means-null-in-typescript but that was unfortunately closed as a duplicate itself, even though it really isn't. There's a fairly big semantic difference between `foo!` meaning that `foo` is asserted to be non-null and `null!` meaning that *`null` itself* is asserted to be non-null. – jcalz Apr 14 '22 at 14:30
  • @samerazeagvvl could you articulate what you are trying to do? The question "why would someone write `null!` in TypeScript" is a good one, but the way it's written here it's not clear if that's what you're asking because you haven't provided a [mre]. Neither `BehaviorSubject` nor `User` are defined here. Could you give us enough info to answer? – jcalz Apr 14 '22 at 14:52

0 Answers0