One of the benefits of using TypeScript is the type system which requires you to provide the correct values between all interactions in your application. For values that can be null
or undefined
, you may need to handle different code paths, for example by using default values.
TypeScript comes with strict null
support by providing a null
type. This is helpful when working with browser APIs. For example, document.querySelector(<selector>)
returns an Element
or null
if the selector doesn’t match any element. But if you’re seeing TypeScript removing the null
type from type definitions and returning the other possible types, this tutorial is for you.
TypeScript Series Overview
- How to Export Transpiled Code From package.json
- Use Nodemon to Restart Your Server on Changes
- How to Allow Trailing Commas (Comma-Dangle) With Typescript-ESLint
- Use SWC to Speed up TypeScript Code
- Fixing Null Type Ignored in Union Type
- How to Remove Index Signature from a Type
- Module Augmentation Overwrites Declarations Instead of Merging Them
- Get All Keys of an Enum
- Get All Values of an Enum
- Using a String as Enum Key
- Understanding “keyof typeof”
- Get Type of Class Properties and Omit Methods
Fix the Missing Null Type in a Union Type
Here’s a basic example describing the problem: you have a method that expects an argument to be either of type string
or a null
. When you’re hovering over the method name inside of Visual Studio Code, the type of the argument is string
. TypeScript removed the null
type. That’s wrong and possibly not intended.
Here’s a sample function outlining the issue:
function sayHelloTo (name: string | null) {
// in VS Code: hover over "sayHelloTo" and the arguments are -> "name: string"
console.log(`Hello ${name}`);
}
Solving the Missing Null Type
Fix the removed null
type in TypeScript by making sure either your tsconfig.json
contains at least one of the following compiler options:
Here’s a sample tsconfig.json
file containing both of the checks:
{
"compilerOptions": {
"target": "ES2021",
// …
// one of these settings is required for the `null` type
"strict": true,
"strictNullChecks": true,
}
}
If you’re referencing a second tsconfig.json
, ensure it’s not overwriting the settings from the first one. And if you’re not seeing the null types showing up in Popovers of Visual Studio Code, you may restart VS Code itself or the Extension Host.
Enjoy the null
type in TypeScript!