I was intrigued by the behavior in TypeScript where line A
compiles successfully while line B
does not.
function someFunction<T>(arg: T): void {
console.log(arg)
}
someFunction<string>('some string') // this works fine
someFunction<string>(null) // line [A] compiles
someFunction<string>(2) // line [B] does not compile
It's interesting that in line A
, the compiler is informed that the argument is of type string
even though it is not. Surprisingly, TypeScript does not throw any errors for this line.
However, in line B, where a number
is passed while hinting it as a string
, the compiler rightly fails to compile.
Why does line A
compile without error? Is there a unique case with the null
type that causes this behavior?
Even after searching online, I could not find a definitive explanation for this discrepancy. Any resources or links explaining this behavior would be greatly appreciated.