Typescript - Object is possibly 'null'.ts(2531) after null check

Viewed 279

I'm getting Object is possibly 'null'.ts(2531) after null check. Can someone help me with it? Am I doing something wrong?

    let array_of_some_data: ({ some_value: number } | null)[] = [];

    //Getting Object is possible 'null' error as expected. Because I didn't check null before trying to access value.
    array_of_some_data[0].some_value = 5;

    //Not getting error as expected since I've checked null this time.
    if (array_of_some_data[0] !== null) array_of_some_data[0].some_value = 5;
    
    //Why am I getting Object is possible 'null' error here? Only difference from above line is I've stored index value in a const.
    const x: number = 0;
    if (array_of_some_data[x] !== null) array_of_some_data[x].some_value = 5;
1 Answers

This issue is a limitation with typescript's control flow analysis for discriminated unions.

Currently, we can use literals such as 0 to narrow the type of an object (or, in this case, an array). However, we can't use constant variables such as x to do this. Typescript's developers decided not to implement this due to performance concerns.

There is an open PR discussing this issue in greater detail. Here

One workaround gives typescript a hand by using an intermediary assignment:

const x: number = 0;
var element_of_some_data = array_of_some_data[x];
if (element_of_some_data) element_of_some_data.some_value = 5;

Alternatively, use the ! operator to tell typescript that we know the value isn't null:

const x: number = 0;
if (array_of_some_data[x] !== null) array_of_some_data[x]!.some_value = 5;
Related