Hone

Lessons · TypeScript · interfaces and optional fields

The shape of an object

interface Name { field: type; other?: type } describes what an object must have; ? marks a field that may be missing.

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

API payloads, props, config: naming the shape once lets every function that takes it be checked, and the editor autocomplete it.

How to think about it

Which fields are always there, and which sometimes? Look at one real example of the object and write down each field and its type. Mark optional what is genuinely sometimes absent, and handle that absence where you read it.

Worked example

interface Product { name: string; price: number; sale?: number }
sale may be missing.
function label(p: Product): string {
Takes the shape; returns text.
  const price = p.sale ?? p.price;
sale is number | undefined; ?? handles the undefined.
  return `${p.name}: ${price}`;
Both fields now safe to use.
}

Your turn

Make the email field optional.

interface User { name: string; email: string }

The trap

Reading an optional field as if it were there: p.sale.toFixed(2) errors with 'possibly undefined'. That error is the compiler doing its job.

Practise interfaces and optional fields on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.