In TypeScript, when invoking a function, why can I hint that a null argument has some other type?

Viewed 58

I was trying to understand how come in TypeScript line A compiles while line B does not.

function someFunction<T>(arg: T): void {
  console.log(arg)
}

someFunction<string>('some string') // obviously, it works
someFunction<string>(null)          // [A] compiles
someFunction<string>(2)             // [B] doesn't compile

In line A, I'm hinting the compiler that the argument is of type string while it is clearly not. However TypeScript will compile that line without emitting any errors.

This doesn't happen in line B. I'm passing a number and hinting that it is a string.

How come line A doesn't fail compiling? Is there a special case with the null type?

Despite my googling, I couldn't find a satisfactory explanation why this is. Providing links to resources explaining what is going on in my code is very welcome.

1 Answers

Unless you enable strictNull checking in your tsconfig.json, all types have implicitly undefined and null types. So when you type string, it is basically string | undefined | null. I definitely recommend enabling that option because it will catch alot of unwanted bugs.

You can read more about it here: https://basarat.gitbook.io/typescript/intro/strictnullchecks

Related