Hone

Lessons · TypeScript · a property that may not be there

A property that may be missing

nick?: string means the property may be absent; its type is really string | undefined, and you must check it before using it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Optional fields are everywhere in real data. The compiler refuses p.nick.length because the day nick is missing, that line crashes.

How to think about it

Check, or use optional chaining with a default: p.nick?.length ?? 0. Mark a property optional only when absence is a valid state, not to silence an error.

Worked example

interface P { nick?: string }
nick may be absent.
const p: P = {};
Allowed.
p.nick.length;
Error: nick may be undefined.
console.log(p.nick?.length ?? 0);
0: optional chaining and a default handle the missing case.

Your turn

Make the note optional.

interface Order { note: string }

The trap

Optional means string | undefined, not string | null. A null from JSON is a different type and needs its own check.

Practise a property that may not be there on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.