TypeScript object types define the expected properties, value types, optional fields, and read-only access rules for structured JavaScript objects.
property?: type: Optional property (may be omitted or undefined).readonly property: type: Immutable property (cannot be reassigned after object creation).[key: string]: type: Index signature for dynamic key-value maps.// Inline object type annotation
const dbConfig: {
readonly host: string;
port: number;
database: string;
connectionTimeout?: number; // Optional property
} = {
host: "localhost",
port: 5432,
database: "production_db"
};
// Reassigning port is allowed
dbConfig.port = 5433;
// dbConfig.host = "remotehost"; // Error: Cannot assign to 'host' because it is a read-only property
function connectDatabase(config: typeof dbConfig): void {
const timeout = config.connectionTimeout ?? 5000;
console.log(`Connecting to PostgreSQL at ${config.host}:${config.port}/${config.database} (Timeout: ${timeout}ms)`);
}
connectDatabase(dbConfig);
readonly for Immutable Identifiers: Mark database IDs, created timestamps, and API tokens as readonly.config.connectionTimeout?.toString()) when handling optional fields.Create an object type with properties id (readonly number) and nickname (optional string). Initialize an object omitting nickname.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With