Menu

Optional, Readonly, and Dynamic Properties

Lesson 3: Optional, Readonly, and Dynamic Properties

Which property modifiers are there?

Modifier or form Syntax Meaning
Optional discount?: number May be missing
Read-only readonly id: string Cannot be reassigned after creation
Index signature [sku: string]: number Any number of keys of this type
Record<K, V> Record<string, number> Object with keys K and values V
Record with a literal union `Record<'UPI' 'Card', number>`

Example

interface Order {
  readonly id: string;
  readonly createdAt: Date;
  status: 'pending' | 'shipped' | 'delivered';
  couponCode?: string;
}

const order: Order = { id: 'QC-1042', createdAt: new Date(), status: 'pending' };
order.status = 'shipped'; // OK
order.id = 'QC-9999';
// Error: Cannot assign to 'id' because it is a read-only property.

// Index signature: stock level per SKU
const stock: { [sku: string]: number } = { 'MILK-1L': 40, 'RICE-5KG': 12 };
stock['EGGS-12'] = 30;

// Record with fixed keys: every method must have a fee
type PaymentMethod = 'UPI' | 'Card' | 'COD';
const fees: Record<PaymentMethod, number> = { UPI: 0, Card: 0, COD: 2500 };

How it works

  • readonly is checked only by TypeScript. At runtime the object is still mutable, so it prevents accidental changes in your code, not deliberate ones.
  • An index signature allows any key, so reading stock['UNKNOWN'] gives number even though the value is undefined. Enable noUncheckedIndexedAccess to get number | undefined.
  • Record with a literal union forces every key to be present, which is great for lookup tables: adding a new payment method makes the compiler show every table that needs updating.
  • Under exactOptionalPropertyTypes, couponCode?: string means "missing or a string", and assigning undefined explicitly is an error.

Common mistakes

Mistake Effect Fix
Using an index signature for a fixed set of keys Typos allowed, missing keys not caught Use `Record<'a'
Expecting readonly to freeze objects Values can still change at runtime Use Object.freeze for runtime immutability
Making many properties optional "just in case" Lots of undefined checks Make only truly optional fields optional

Key takeaways

  • Use ? for missing values, readonly for values that must not change, and Record or index signatures for dynamic keys.
  • A Record keyed by a literal union keeps lookup tables complete.

Try it: Create a Record that maps each delivery slot ('morning' | 'afternoon' | 'evening') to a time range string, then add a new slot and see where the compiler complains.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details