TypeScript Foundations·Types that pay for themselves

Objects and readonly

Describe the shape of an object once and let the compiler keep every use of it honest.

Intermediate 11 min read Lesson 3 of 300 Challenge included
What you will be able to do
  • Write an object type literal to describe an objects shape.
  • Mark properties that may be absent with a question mark.
  • Use readonly to block accidental changes to a property.
  • Use a Record type for maps where every value shares one type.

In plain English

An object type literal describes an object by listing its properties and their types. An optional property is one that may be missing and is written with a question mark. The readonly modifier says a property may be set once but never changed afterwards. An index signature lets an object hold any number of properties that all share one value type. The built-in Record type is a shorthand for that same idea when the keys are strings.

Step by step

  1. 1List each property and its type inside curly braces.
  2. 2Add a question mark to properties that can be missing.
  3. 3Put readonly before a property that must not change.
  4. 4Use a Record type for a lookup where keys are strings.
  5. 5Assign an object and let the compiler check it matches the shape.
objects.tsTypeScript
type Lesson = {
  id: string
  title: string
  readonly slug: string
  published?: boolean
}

const lesson: Lesson = {
  id: '1',
  title: 'Objects and readonly',
  slug: 'objects-and-readonly',
}

const scores: Record<string, number> = {
  quiz: 9,
  challenge: 8,
}

const counts: { [key: string]: number } = {
  lessons: 5,
  minutes: 55,
}

Common mistakes

  • Adding every possible property up front makes a type harder to use, so only model real data.
  • Forgetting the question mark on an optional property forces every object to include it.
  • Assigning a new value to a readonly property causes a compiler error because the type forbids it.
  • Using any as a shortcut removes the safety the object type was supposed to give you.
Your turn

Model a credential

Easy

Create a Credential type with id, holder and a readonly program, plus an optional score. Then build one valid object.

TYPESCRIPT · starter
type Credential = {}

const credential: Credential = {}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does readonly prevent you from doing?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Narrowing in practice
Lesson 3 of 300 · 0% of course