Course outline · 0% complete

0/26 lessons0%

Course overview →

Optional and Readonly Properties

lesson 3-2 · ~11 min · 9/26

Not every property is always there

Real data has gaps: a profile might not have a bio yet. Mark a property optional with ?:

interface Profile {
  readonly id: number;
  username: string;
  bio?: string;
}

bio?: string means the property is either a string or absent. TypeScript then forces you to handle the absent case: p.bio.length is an error until you check, for example if (p.bio !== undefined). That check is your first taste of narrowing, which Unit 4 covers properly.

readonly id means the property can be set when the object is created and never reassigned afterwards. p.id = 99 is a compile error. Like const for a single property, and like everything else in TypeScript, it is enforced only at compile time.

Code exercise · typescript

Run it. The first call omits bio entirely, which is legal because bio is optional. Then add a line p.id = 99 inside show and run again to see readonly enforced. Note the void return type: show prints instead of returning a value.

Quiz

With bio?: string, what is the actual type of p.bio when you read it?

A one-line if: the conditional operator

The next exercise needs a value that depends on a condition: the mark is "[x]" when a task is done, "[ ]" otherwise. JavaScript has an expression form of if/else built for exactly this, the conditional operator (often called the ternary operator, because it takes three parts). It has not appeared in your courses so far, so here is the whole rule:

const mark = t.done ? "[x]" : "[ ]";

Read condition ? a : b as: evaluate the condition, produce a if it is true, otherwise produce b. It exists because an if/else statement cannot sit on the right side of an = — the conditional operator is an expression, so it produces a value you can assign, return, or pass as an argument. TypeScript checks both arms like any other expression, so a typo in either branch is still caught.

Code exercise · typescript

Your turn. Declare interface Task with title (string), done (boolean), and an optional due (string). Write report(t: Task): string that returns "[x] " or "[ ] " plus the title, and appends " (due ...)" only when due is present. Print the two calls shown in the starter comments.