When working with javascript I always assumed that the double NOT operator (!!) behaves the same way as Boolean(), when trying to get a true / false out of a statement; however, since working with TypeScript I recently came across a scenario where they behaved differently, and I am trying to understand why that is. Take the following code for example:
import React from 'react'
interface Props {
myNumber: number | null
}
const Test: React.FC<Props> = ({ myNumber }) => {
return (
<>
{/* Example 1 */}
{!!myNumber && <span>{myNumber.toString()}</span>}
{/* Example 2 */}
{Boolean(myNumber) && <span>{myNumber.toString()}</span>}
</>
)
}
export default Test
Under example #1 the code works as I expect it: If the is rendered that means that myNumber passed the !! check, so it can never be null, thus myNumber.toString() will not return an error.
Under example #2 however, myNumber.toString() will return an error stating that "Object is possibly null", even though this code should only be reached if the Boolean(myNumber) returns true, and Boolean(null) should always be false.
Am I wrong thinking they should behave exactly the same? Is there something related to the TypeScrtipt compiler that I am missing? Thanks!