Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

>! is just an inline type coercion.

Are you sure about that? It sounds more like a signal to the compiler to "trust me, I know what I'm doing" and would blow up if you passed undefined anyway. Maybe the author didn't explain it very well. That is, not a type coercion so much as a hint to not bother checking this access.



When would code with ! ever compile differently than code without ! ?


Umm never? That's not the point. It's not changing (coercing) the type of anything, it's just allowing the call without flagging it as an error. The call at run time might still get passed an undefined and fail. It's like choosing an unsafe partial function in Haskell rather than using a total function that forces you to deal with Maybe.

At least that's what it looks like. I've never used typescript or I'd test it right now. I'm on my phone and haven't tried it.

(Edit: my answer didn't quite make sense! It's different since without ! it compiles as an error because, in this case, you can't map over undefined. With !, it just ignores that possibility although it could still happen. The compiler cannot verify all run time possibilities since your sum type says it really can be undefined.)

(Re edit! Verifying the types vs skipping that verification is not the same thing as coercing the types)


It's coercing the type from, e.g. String | undefined to String.


  let lowerCased = (s : string[] | undefined) => s!.map((str : string) => str.toLowerCase());

  console.log(lowerCased(['A','B']));
  console.log(lowerCased(undefined)); //boom!
It doesn't coerce anything. All it does is let the code pass without error. "s!.map" and "s.map" compile to the exact same Javascript code, which means there is no type coercion going on. Are you sure you know what type coercion is? The first log prints out fine and the second blows up, which proves that undefined isn't being coerced to a string[]. If that was the case, the resulting JS would be checking for undefined and probably creating an empty array.


My bad, I meant conversion, not coercion.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: