Lesson 6 of 10
Optional and readonly fields
- 11 min
- 5 checks
- 3 hints
- Go to task
Goal
What may be missing and what never changes
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 ??.
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- No type errors
- bio can be left out
- id can't be changed after creation
- card returns just the name when there's no bio
- card adds the bio with the spaces at both ends removed