TS Object Types
Object types in TypeScript are used to define the structure of objects, including their properties and types. By specifying object types, TypeScript provides better code completion, error checking, and documentation.
Key Topics
Basic Object Types
Object types are defined using an inline type or a type alias. Each property of the object can have a specific type.
type User = {
name: string;
age: number;
};
let user: User = { name: "Alice", age: 30 };
console.log(user.name); // Alice
console.log(user.age); // 30
Output
Alice
30
Explanation: The User
type defines an object with a name
and age
, both of which must be provided when creating an object of this type.
Optional Properties
Properties can be marked as optional using the ?
operator. Optional properties are not required but can still be included.
type Car = {
make: string;
model?: string;
};
let car: Car = { make: "Toyota" };
console.log(car.make); // Toyota
console.log(car.model); // undefined
Output
Toyota
undefined
Explanation: The model
property is optional, so it does not need to be included in every object of type Car
.
Readonly Properties
Properties can be marked as readonly
, preventing them from being modified after the object is created.
type Point = {
readonly x: number;
readonly y: number;
};
let point: Point = { x: 10, y: 20 };
// point.x = 15; // Error: Cannot assign to 'x' because it is a read-only property
console.log(point.x); // 10
console.log(point.y); // 20
Output
10
20
Explanation: The readonly
modifier ensures that the properties x
and y
cannot be modified after the object is initialized.
Nested Objects
Object types can be nested to describe objects containing other objects.
type Address = {
street: string;
city: string;
};
type Person = {
name: string;
address: Address;
};
let person: Person = {
name: "John",
address: { street: "Main St", city: "Springfield" }
};
console.log(person.name); // John
console.log(person.address.city); // Springfield
Output
John
Springfield
Explanation: The Person
type contains a nested Address
type, allowing you to describe complex object structures.
Key Takeaways
- Object Types: Define the structure of objects with specific property types.
- Optional Properties: Use
?
for properties that are not always required. - Readonly Properties: Prevent modification of properties after initialization.
- Nested Objects: Define complex structures by nesting object types.