Objects and Index Signatures in TypeScript
Defining object types in TypeScript: optional properties (?), readonly modifiers, index signatures, and Record<K, V> utility.
Objects and Index Signatures in TypeScript
TypeScript allows you to declare precise object shapes with optional, required, and immutable properties.
1. Object Type Declarations
type UserProfile = {
readonly id: string; // Cannot be reassigned after initialization
username: string;
email: string;
avatarUrl?: string; // Optional property (string | undefined)
};
const user: UserProfile = {
id: "usr_102",
username: "iamtashanto",
email: "alex@example.com",
};
// β Error: Cannot assign to 'id' because it is a read-only property.
// user.id = "usr_999";2. Dynamic Keys with Index Signatures
When you don't know the property names in advance (e.g. dictionary / lookup map), use an Index Signature:
type HeaderDictionary = {
[headerName: string]: string | undefined;
};
const requestHeaders: HeaderDictionary = {
"Content-Type": "application/json",
"Authorization": "Bearer token123",
"X-Custom-Header": undefined,
};3. Record<K, V> Utility Type
Record<Keys, ValueType> is a cleaner shorthand for index signatures when key names belong to a specific set:
type Environment = "development" | "staging" | "production";
const apiEndpoints: Record<Environment, string> = {
development: "http://localhost:3000/api",
staging: "https://staging.api.example.com",
production: "https://api.example.com",
};Related Topics
Arrays and Tuples in TypeScript
Annotating arrays in TypeScript: type[] syntax, Array<T> generic, readonly arrays, and fixed-length typed Tuples.
Functions and Signatures in TypeScript
Typing functions in TypeScript: parameter types, return type inference, optional/default parameters, function types, and function overloads.