BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
📦

Object Types: Describing an Object's Shape

💡 An object type lists each property and its type inline, letting TypeScript verify an object's exact shape — and ? marks a property as optional.

So far you've met simple types like string and number. But most real data comes bundled together — a user has a name and an age. In TypeScript, you describe the shape of an object by listing its properties and each property's type, right in the annotation. This is an object type, and writing it directly in place is called an inline or anonymous object type.

ts
function greet(person: { name: string; age: number }) {
  return `Hello ${person.name}, age ${person.age}`;
}

greet({ name: "Ada", age: 36 }); // ✅

Each property is written name: type, separated by ; (or ,). TypeScript now checks every call: the argument must have a name that is a string and an age that is a number. Pass { name: "Ada" } and you get an error — the age property is missing. Pass an extra property it doesn't list, or the wrong type, and it complains too.

You can make a property optional by adding ? after its name. An optional property may be present or absent, so before using it you should check it isn't undefined:

ts
function greet(person: { name: string; age?: number }) {
  const suffix = person.age !== undefined ? `, age ${person.age}` : "";
  return `Hello ${person.name}${suffix}`;
}

greet({ name: "Ada" });          // ✅ age omitted
greet({ name: "Ada", age: 36 }); // ✅ age given

Inline object types are perfect for one-off shapes. When you find yourself repeating the same shape, that's the signal to give it a name with an interface or type alias — a topic for a later card.