Objects
Intro to Objects
Objects are the fundamental way to group related data in TypeScript. Instead of
having separate variables, you combine them into a single structure.
// Without objects - scattered data
const userName = 'Alice'
const userAge = 30
const userEmail = 'alice@example.com'
// With objects - organized data
const user = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
}
Typing Objects
TypeScript can infer object types, but you can also be explicit:
const user: { name: string; age: number; email: string } = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
}
Naming Object Types
Once you repeat a shape, it helps to name it:
type User = { name: string; age: number; email: string }
const user: User = {
name: 'Alice',
age: 30,
email: 'alice@example.com',
}
Property Access
Access properties with dot notation or bracket notation:
// getting values
console.log(user.name) // "Alice"
console.log(user['email']) // "alice@example.com"
// setting values
user.name = 'Bob'
user['friendship-status'] = 'friends'
Optional Properties
Not every property is always present. Use
? for optional properties:type UserProfile = { name: string; nickname?: string }
const user: UserProfile = {
name: 'Alice',
// nickname is optional, so we can omit it
}
Objects in TypeScript are the building blocks for modeling real-world entities
like users, products, orders, and more.
In this exercise, you'll create and work with typed objects.