Thuta Learning
TypeScript
IntermediateProgrammingIntermediate

Objects

TypeScriptLesson 925 min

What you'll walk away with

  • Write an inline object type, then name and reuse it with a type alias
  • Use optional (?) and readonly properties, handling the optional value with an undefined check
  • Explain how excess property checks and structural typing work
  • Use Record<string, T> for a dictionary whose keys are not known in advance

Explain it simply

Explain it simply

Think of an object type as the template for a form. Just as a form fixes its boxes in advance, "Name: text" and "Age: number", the type { name: string; age: number } says the object must have a name and an age property, and which type each one holds.

When you fill in the form, TypeScript points out a missing box, a misspelled box name or text where a number belongs. It also warns you when you try to read a property that the template does not have.

Problem → Why → Solution

The problem: a typo quietly becomes undefined

In JavaScript, reading a property that does not exist is not an error; you just get undefined. So a single typo, emial instead of email, makes the app try to send a welcome email to the address "undefined". On the building side, nobody notices a missing field or an age stored as a string either, until some later code that uses the data produces strange results.

signup.js
// Plain JavaScript: the object's shape lives only in your head
const user = { name: "Aye Aye", email: "aye@example.com", age: "29" };

function sendWelcome(u) {
  console.log("Sending to " + u.emial); // typo: prints "Sending to undefined"
}

sendWelcome(user);
const nextYear = user.age + 1; // "291", not 30

Why does this happen?

JavaScript objects have no declared shape: you can read any property and store any type. Give the object a type and TypeScript reports "Property 'emial' does not exist... Did you mean 'email'?" and rejects age: "29" because it is not a number.

Core concept: an object type describes a shape

You write an object type as { property: Type; property: Type }. It can sit inline on a variable, but if the shape is used in several places, name it with a type alias such as type User = { ... }. Then function parameters, return types and array elements simply say User. (A similar syntax, interface, comes in a later lesson.)

Two modifiers make properties more precise. The ? in nickname?: string means the property may be absent, so reading it gives string | undefined and you must check it with ?? or an if before use. readonly id: number forbids changing the property after the object is created. readonly is checked only at compile time and is shallow: with readonly tags: string[] you cannot assign a new array to tags, but tags.push() still works.

TypeScript checks objects structurally: it looks at the shape, not at a name. Where a User is expected, any object that has all of User's properties is accepted, even with extra properties. There is one exception. When you write an object literal directly where a type is expected, the excess property check runs, so putting { name: "A", age: 3 } into { name: string } gives "Object literal may only specify known properties". In a fresh literal an unexpected property is most likely a typo.

The checking happens on both sides. When building an object, a missing required property gives "Property 'age' is missing" and a wrong type gives "Type 'string' is not assignable to type 'number'". When reading, a property that is not in the type gives "Property 'emial' does not exist". Nested objects are checked the same way at every level, so even the city in user.address.city is spell-checked.

Mental model: a form template
  1. The type defines the form's boxes
  2. Building an object checks every box
  3. A ? box may be undefined
  4. Reading checks the property name

Any mismatch with the declared shape is a compile error, both where the object is built and where it is read.

General pattern

typescript
type Name = {
  required: Type;
  optional?: Type;          // Type | undefined when read
  readonly fixed: Type;     // cannot be reassigned
  nested: { inner: Type };
};

const value: Name = { required: ..., fixed: ..., nested: { inner: ... } };

Each property is written name: Type;. ? makes it optional and readonly blocks reassignment. Object types can be nested inside each other.

Example: an inline object type

The simplest form writes the type directly on the variable. This object is used in only one place, so it does not need an alias yet; the deeper section shows how to name the shape and reuse it.

typescript
const person: { name: string; age: number } = {
  name: "John Doe",
  age: 30
};

console.log(`${person.name} is ${person.age} years old.`);

Code breakdown

  1. Line 1const person: { name: string; age: number } = {

    The { name: string; age: number } after the colon is an inline object type: person must have both properties with the right types.

  2. Line 2name: "John Doe",

    name must be a string. Misspell it as nmae and an excess property error, "'nmae' does not exist in type", points straight at this line.

  3. Line 3age: 30

    age is a number. Writing age: "30" gives "Type 'string' is not assignable to type 'number'".

  4. Line 6console.log(`${person.name} is ${person.age} years old.`);

    Reading person.name and person.age gets autocomplete, and reading a missing property such as person.email is an error.

You should see
John Doe is 30 years old.

Type aliases, optional, readonly and nested objects

The User type is declared once and reused for two objects and a function. nickname is optional, so displayName() falls back to name with ??. Building a new object with a spread (...aye) is still checked against the User shape.

user.ts
type User = {
  readonly id: number;
  name: string;
  nickname?: string;
  address: { city: string; country: string };
};

function displayName(user: User): string {
  return user.nickname ?? user.name;
}

const aye: User = {
  id: 1,
  name: "Aye Aye",
  address: { city: "Yangon", country: "Myanmar" },
};
const ko: User = { ...aye, id: 2, name: "Ko Ko", nickname: "KK" };

console.log(displayName(aye), "-", aye.address.city);
console.log(displayName(ko), "-", ko.address.country);

When keys are not known in advance: Record

For objects whose keys only appear at runtime, such as a stock list, use Record<string, number>: any number of string keys, every value a number. Be careful: reading a key that does not exist is still typed number, even though the value is undefined.

stock.ts
const stock: Record<string, number> = { apple: 12, mango: 0 };
stock.banana = 30;

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count}`);
}

const papaya = stock["papaya"]; // typed number, value undefined
console.log(papaya);

In real projects

Where this shows up in real projects

Every real app has domain objects: User, Product, Order, Invoice. Teams declare these shapes once as type aliases, often in a file such as types.ts, and reuse them for React component props, API responses, database rows and form state. Adding or renaming a field on Order then makes the compiler point at every place that uses that shape.

Optional properties honestly describe data that is not always there: a user who has not uploaded a profile picture, or an order with no trackingNumber because it has not shipped yet. readonly fits fields that should never change, such as id or createdAt. Remember that an annotation does not check at runtime whether JSON from a server really matches the type, so the API boundary still needs its own validation.

Common mistakes

Common mistakes

1. Using an optional property without a check

With nickname?: string, user.nickname.toUpperCase() fails with "'user.nickname' is possibly 'undefined'". Silencing it with ! (a non-null assertion) crashes at runtime for users without a nickname. Use user.nickname?.toUpperCase() or a ?? fallback.

2. Thinking readonly freezes the object

readonly is a compile-time check only and disappears from the JavaScript output. It is also shallow: with readonly items: string[], items.push() still works. Use readonly string[] to protect the array too, and Object.freeze() if you need runtime protection.

3. Expecting the excess property check everywhere

The check only runs on object literals written in place. const extra = { name: "B", age: 4 }; assigned later to { name: string } is fine, because structurally having name is enough. That is how an object carrying extra fields, such as a password, can leak into an API response; copy only the fields you need.

Best practices

Best practices

  • Once a shape is used in more than two places, give it a type alias instead of repeating an inline type.
  • Make a field optional only when it genuinely can be missing; unnecessary ? marks spread undefined checks everywhere.
  • Mark fields that should never change, such as id and createdAt, as readonly.

Mini challenge

Mini challenge: a product catalog

Declare a Product type, compute the final price including any discount, and print one line per product.

  • Product has a readonly sku, name, price and an optional discountPercent
  • finalPrice(product) treats a missing discountPercent as 0
  • describe(product) adds a tag like " (-25%)" when there is a discount
  • Test with two products, one with a discount and one without
catalog.ts
type Product = {
  // TODO: readonly sku, name, price, optional discountPercent
};

function finalPrice(product: Product): number {
  // TODO: apply discountPercent (missing means 0)
}

function describe(product: Product): string {
  // TODO: "MUG-02 Clay mug: 9.00 (-25%)"
}

// TODO: create two products and print describe() for each

Expected: TEA-01 Green tea: 4.00 MUG-02 Clay mug: 9.00 (-25%)

Show hint

product.discountPercent ?? 0 turns the optional value into a plain number. Show prices with two decimals using toFixed(2).

Show solution
catalog.ts
type Product = {
  readonly sku: string;
  name: string;
  price: number;
  discountPercent?: number;
};

function finalPrice(product: Product): number {
  const discount = product.discountPercent ?? 0;
  return product.price * (1 - discount / 100);
}

function describe(product: Product): string {
  const tag = product.discountPercent ? ` (-${product.discountPercent}%)` : "";
  return `${product.sku} ${product.name}: ${finalPrice(product).toFixed(2)}${tag}`;
}

const catalog: Product[] = [
  { sku: "TEA-01", name: "Green tea", price: 4 },
  { sku: "MUG-02", name: "Clay mug", price: 12, discountPercent: 25 },
];

for (const product of catalog) console.log(describe(product));

Quick quiz 1 / 3

What happens with const p: { name: string } = { name: "Aye", age: 3 };?

Quick quiz 2 / 3

Given type User = { nickname?: string }, what is the type of user.nickname when you read it?

Quick quiz 3 / 3

With const box: { readonly tags: string[] } = { tags: [] };, which line is a compile error?

What to remember

  • An object type { prop: Type } lists the properties an object must have; a type alias names it for reuse.
  • ? makes a property optional (read as Type | undefined); readonly blocks reassignment at compile time and is shallow.
  • TypeScript compares shapes; the excess property check only applies to object literals written in place.
  • Use Record<string, T> when keys are not known in advance, and remember that missing keys read as undefined.

TypeScript Handbook — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Objects | Thuta Learning