When using the --strictNullChecks
flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is proving challenging).
Consider an interface Foo
with an optional property:
interface Foo {
bar?: {
baz: string;
};
}
The following code successfully compiles:
//compiles
function doStuff(foo: Foo) {
if (foo.bar === undefined) {
throw new Error("foo.bar must be defined");
}
foo.bar.baz;
}
However, this code does not compile due to tsc potentially identifying foo.bar
as undefined:
//does not compile, foo.bar can be undefined
function doStuff2(foo: Foo) {
validateFoo(foo);
foo.bar.baz;
}
function validateFoo(foo: Foo) {
if (foo.bar === undefined) {
throw new Error("foo.bar must be defined");
}
}
Why does this happen? Is there a way to specify a function for handling undefined and null checks without resorting to foo.bar!.baz
? While it may be simple to inline the if/throw statement in this example, it becomes repetitive when dealing with multiple optional properties within Foo
across different functions.