Skip to content
dreamcode
dreamcode
Map
Object types
Lesson 5 of 26
+15 XP on finish
TS BASICSChapter 1 · TS Basics

Object Types and Optional Properties

You can describe an object's shape right where you use it: star: { name: string; mag?: number }. A ? makes a property optional: it may be missing, so its type includes undefined, and TypeScript makes you check before using it. Object literals are checked exactly: a missing required property and a misspelled extra one are both errors.

Worked example

How it reads

  • mag?: number means the property can be left out
  • Checking === undefined narrows mag to a plain number afterwards
  • When the shape is used in many places, give it a name with an interface
Cloud tip: value ?? fallback supplies a default only when the value is null or undefined.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Add an optional moons?: number to the parameter type, and make label return Mars (2 moons) when moons is given. Log label({ name: "Mars", moons: 2 }).

Press Run to check your work.