Objects and readonly
Describe the shape of an object once and let the compiler keep every use of it honest.
- 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
- 1List each property and its type inside curly braces.
- 2Add a question mark to properties that can be missing.
- 3Put readonly before a property that must not change.
- 4Use a Record type for a lookup where keys are strings.
- 5Assign an object and let the compiler check it matches the shape.
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.
Model a credential
Create a Credential type with id, holder and a readonly program, plus an optional score. Then build one valid object.
type Credential = {}
const credential: Credential = {}What does readonly prevent you from doing?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.