Miguel Moura
Miguel Moura

Reputation: 39524

Object is possibly 'null' when using ternary operator

I have the following in Typescript 4 and using Strict Mode:

let userId = parameters.has('userId') ? +parameters.get('userId') : undefined;

I get the compilation error Object is possibly 'null'. on the part:

+parameters.get('userId')

The method parameters.get returns string | null ...

How can I avoid this error?

Upvotes: 0

Views: 1081

Answers (1)

Tal Ohana
Tal Ohana

Reputation: 1138

There are couple of options to solve this, I'll start with what's not recommended and it is to use TypeScript's ! operator, also known as non-null assertion

const userId = parameters.has('userId') ? +!parameters.get('userId') : undefined;

This way you are telling TypeScript's compiler: "I know better the type and I guarantee it is not null". It is not recommended to use it because the value can potentially be null under certain conditions.

The second approach is to separate into two steps, first extract the parameter and then check if it defined, the only drawback is that empty string '' will be converted to undefined

const userIdParam = parameters.get('userId');
const userIdOptionOne = userIdParam ? +userIdParam : undefined;

You can play with both of these examples in this TypeScript playground

Upvotes: 1

Related Questions