typescript non null assertion code example
Example 1: typescript null and undefined check
if(!!someValue)
Example 2: typescript null and undefined check
let x = foo?.bar.baz();
Example 3: typescript assert non null
interface Foo { bar(): void }
declare function getFoo(): Foo | undefined;
function assert(value: unknown): asserts value {
if (value === undefined) {
throw new Error('value must be defined');
}
}
function test() {
const foo = getFoo();
// foo is Foo | undefined here
assert(foo);
// foo narrowed to Foo
foo.bar();
}