In TypeScript, an object type defines the structure of an object by specifying its properties, their types, and any additional constraints. Object types allow you to define flexible and reusable data shapes with strong typing.
Syntax for Object Types
type MyObjectType = { propertyName: PropertyType; anotherPropertyName?: AnotherPropertyType; // Optional property };
Key Features of Object Types
- Defining Properties: Each property has a name and a type. You can specify required or optional properties.
Example Usage:type User = { name: string; // Required age: number; // Required email?: string; // Optional };
const user1: User = { name: "Alice", age: 25 }; const user2: User = { name: "Bob", age: 30, email: "bob@example.com" };
- Optional Properties: Add
?
to make a property optional. If not present, its value will beundefined
.type Config = { theme?: string; // Optional }; const config: Config = {}; // Valid
- Readonly Properties: Use the
readonly
modifier to prevent changes to a property after initialization.type Immutable = { readonly id: string; name: string; }; const obj: Immutable = { id: "123", name: "Test" }; // obj.id = "456"; // Error: Cannot assign to 'id' because it is a read-only property.
- Index Signatures: Define objects with dynamic keys.
type Dictionary = { [key: string]: string; // All properties must have string keys and string values. }; const myDict: Dictionary = { firstName: "Alice", lastName: "Smith", };
- Nested Object Types: Object types can include other object types as properties.
type Address = { street: string; city: string; }; type User = { name: string; address: Address; }; const user: User = { name: "John", address: { street: "123 Main St", city: "New York", }, };
- Union and Intersection Types: Combine object types using union (
|
) or intersection (&
).type Admin = { role: "admin"; permissions: string[]; }; type Guest = { role: "guest"; }; type User = Admin | Guest; const user: User = { role: "admin", permissions: ["read", "write"] }; // Valid
Utility Types for Objects
TypeScript provides utility types for working with objects:
- Partial: Makes all properties optional.
type PartialUser = Partial<User>; const user: PartialUser = {};
- Required: Makes all properties required.
type RequiredUser = Required<User>;
- Pick: Selects a subset of properties.
type NameOnly = Pick<User, "name">;
- Omit: Excludes specific properties.
type WithoutAge = Omit<User, "age">;
- Record: Creates an object type with specified keys and value types.
type Roles = "admin" | "editor" | "viewer"; type RoleConfig = Record<Roles, boolean>; const roles: RoleConfig = { admin: true, editor: false, viewer: true, };
Summary
Object types in TypeScript are a cornerstone of its type system, providing precise control over object shapes. With features like optional properties, readonly properties, index signatures, and utility types, you can create robust and maintainable code that benefits from strong typing and IntelliSense.