Menu

Object Types

Lesson 1: Object Types

How do you describe an object?

List each property with its type inside curly braces, separated by semicolons or commas.

Syntax Meaning
{ name: string } Required property
{ email?: string } Optional property (may be missing)
{ address: { city: string } } Nested object
{ items: Product[] } Property holding an array

Example

function printLabel(order: {
  id: string;
  customerName: string;
  address: { line1: string; city: string; pincode: string };
  instructions?: string;
}) {
  console.log(`${order.id} → ${order.customerName}, ${order.address.city} ${order.address.pincode}`);
  if (order.instructions) {
    console.log(`Note: ${order.instructions}`);
  }
}

printLabel({
  id: 'QC-1042',
  customerName: 'Vikram S',
  address: { line1: '12 Anna Salai', city: 'Chennai', pincode: '600002' },
});

How it works

  • The parameter's type describes exactly which properties the function may use.
  • instructions? is optional, so its type inside the function is string | undefined. You must check it before using string methods.
  • Pincodes are strings, not numbers, because they are identifiers and may start with zero.
  • Inline types work, but repeating them in several functions quickly becomes messy. Lesson 2 names them.

Common mistakes

Mistake Effect Fix
Using object or {} as a type Almost no checking; properties not accessible Describe the actual properties
Storing identifiers like pincodes as number Leading zeros lost, arithmetic allowed Use string
Repeating the same inline shape everywhere Shapes drift apart Give it a name with type or interface

Key takeaways

  • Object types list each property and its type.
  • Optional properties include undefined, so check them before use.

Try it: Write a function that accepts a { name: string; price: number; discountPercent?: number } and returns the final price.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details