Lesson 6 of 10

Optional and readonly fields

Goal

What may be missing and what never changes

01

Explanation

Not every field is always there. bio?: string means the bio may be missing, so when you read it, its type is string | undefined, and the compiler rejects p.bio.trim() until you've made sure it exists.

readonly id: number stops anyone from assigning a new value to the field after the object is created, so the ID is written once and never changes. It's a rule only the compiler checks, though: it doesn't freeze the object at runtime the way Object.freeze does.

Be careful with the non-null assertion !. Writing p.bio!.trim() silences the compiler, but it doesn't stop the program from crashing. The right fix is to actually handle the missing value, with a condition or with ?. and ??.

02

Your task

Make bio optional and id readonly, then fix card so that it returns just displayName when there's no bio, and displayName + " — " + bio when there is one, after removing the spaces at both ends of the bio with trim.

Checks

5 checks
  1. No type errors
  2. bio can be left out
  3. id can't be changed after creation
  4. card returns just the name when there's no bio
  5. card adds the bio with the spaces at both ends removed
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.