TypeScript

Using optional chaining vs direct access on null in TypeScript

TypeScriptAdvanced TypesOptional Chainingbeginner

What this snippet does

Optional chaining returns undefined safely, while direct access throws a runtime error if the object is null.

Expected output

undefined
TypeError: Cannot read properties of null (reading '0')

Why practise typing this

Typing advanced types code builds muscle memory for the symbols and indentation TypeScript uses most, which prose-based typing tests never cover. DevType measures your words per minute and accuracy on this snippet and tracks the individual characters you mistype, so later lessons can target them.

More TypeScript practice

Browse all TypeScript snippets →