You can accomplish this by writing a nullable utility function:
const nullable = <T>(a: T) => a as T | null;
let myVar = nullable({ a: 1, b: 2 });
myVar = null; // Valid!
This does introduce an extra function call at variable initialization time, but likely this won't affect you much in most real world scenarios. The code is fairly clean, so I'm a fan of this solution.
One other not so great way to do this would be the following:
const fake = { a: 1, b: 2 };
let realVar: typeof fake | null = fake;
realVar = null;
The downsides are as follows:
- The code is somewhat cryptic to those not very familiar with TypeScript
- You have an extra runtime variable assignment for no reason
- The code still isn't that concise