The point of declaring an optional property or parameter is to make explicit the fact that it might contain no valid value, i.e. null
or undefined
. Using a non-null assertion (the !.
operator) will lead to a runtime error if the optional does contain
null
or undefined
. Even if the value is tested first, it's still considered a bad practice to use a non-null assertion.
function doTheThing(foo?: Foo) { let s = foo!.bar; // Noncompliant }
function doTheThing(foo?: Foo) { if (foo) { let s = foo.bar; } }