3

In typescript 2.2, when strictNullChecks option is true, how to declare a nullable object literal variable :

let myVar = { a: 1, b: 2 };
myVar = null; // Error can not assign null

The only ways I found is :

// Verbose
let myVar: { a: number; b: number; } | null  = { a: 1, b: 2 };

// Bad, same as having no type
let myVar: any| null  = { a: 1, b: 2 };
1
  • 1
    There is no way to do this. You need to explicitly declare the union type. To write less, you can define an interface for the object. Commented Mar 28, 2017 at 17:46

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.