0

In TypeScript, despite checking for null on a nullable field in an object array (with strictNullCheck set to true), the compiler still complains that the 'Object is possibly undefined'. Consider the following:

interface IA {
    d?: Date
}
const arr : IA[] = [{d: new Date()}];

console.error(arr[0].d == null ? "" : arr[0].d.toString());  
                                           // ^ complains that "Object is possibly 'undefined'

Link to TS PlayGround (set strictNullCheck on)

However, if we have:

const a : IA = {d: new Date()};
console.error(a.d == null ? "" : a.d.toString());

then the compiler is happy.

Why is this the desired behavior? And what would be the correct practice here if I don't want to turn strictNullCheck off?

1 Answer 1

5

TypeScript doesn't track array elements by their index; in other words there's no mechanism in the type system that identifies that two expressions arr[0] are necessarily pointing to the same object.

In general this is a good assumption because the ordering of array elements is not guaranteed to remain the same between any two observations of the same element. We can tell from inspection that e.g. you didn't call sort between those two accesses, but in any other case where two expressions aren't evaluated right after the other, it's not known for sure that arr[0] points to the same object both times.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but here the expressions are evaluated one after the other, so I'm just missing the point on why this is different from a var (which can also be mutated by a nested function or such)
You know that, but TypeScript has not implemented a special case to identify that situation
OK, don't complete understand still, but maybe that's not the objective.. what is the recommended practice here then (if I don't want to suppress strictNullCheck)?
Extract it to a const or use the postfix ! operator (arr[0].d!.toString())
It's easier to understand if your mental model of how TS work is "A set of heuristics and tracking rules identify when two expressions resolve to the same object" instead of "TS starts with a perfect model of the universe and discards data on purpose"

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.