Objects and interfaces¶
This lesson explains how to describe object shapes, when to use interface versus type, and how to model optional, readonly, and nested data.
Interfaces¶
An interface defines a contract for an object.
A variable that satisfies the interface can be used anywhere the interface is expected.
Optional and readonly properties¶
readonlystops the property from being reassigned through this type.?makes the property optional.
Note
readonly is a compile-time check. It does not freeze the object at runtime.
Extending interfaces¶
Use extends to build larger interfaces from smaller ones.
interface Entity {
id: string
createdAt: Date
}
interface Course extends Entity {
title: string
lessons: Lesson[]
}
Type aliases for objects¶
type can also describe objects and can represent things interface cannot, such as unions.
For most object contracts, either interface or type works. A common convention is to use interface for object shapes that may be extended, and type for unions, tuples, and computed types.
Index signatures¶
When an object has a dynamic set of keys, use an index signature.
interface Gradebook {
[studentId: string]: number
}
const grades: Gradebook = {
'stu-1': 92,
'stu-2': 87,
}
Nested shapes¶
Types can reference other types.
interface Address {
city: string
country: string
}
interface Contact {
name: string
address: Address
}
Hands-on: model a course catalog¶
- Create
src/catalog.ts. - Define
interface Lessonwithreadonly id,title,durationMinutes, and optionaldescription. - Define
interface Coursewithid,title,instructor, andlessons: Lesson[]. - Create one
Courseobject with at least two lessons. - Write
function totalDuration(course: Course): numberthat sumsdurationMinutes. - Try to reassign a lesson's
idand observe the compiler error fromreadonly. - Add an index signature to
interface Progressthat maps a lesson id to a booleancompleted.