Lesson

TypeScript Object Types

10 min reading
Free Course

TypeScript Object Types: Shapes, Optional Keys, and Record

TypeScript object types describe the exact property names and value types an object must carry. You can write object types inline for one-off parameters or extract them into reusable type and interface definitions.

TypeScript uses structural typing ("duck typing"): any object that has the required properties with matching types satisfies the contract, even if it was not declared with that type name.

Optional (?), readonly, and Record Properties

Add ? after a property name to mark it optional, add readonly to prevent reassignment after creation, and use Record<K, V> for dynamic key-value maps.

function printUser(user: {
  readonly id: number;
  name: string;
  nickname?: string;
}): void {
  const display = user.nickname ?? user.name;
  console.log(`#${user.id}: ${display}`);
}

const featureFlags: Record<string, boolean> = {
  darkMode: true,
  betaEditor: false,
};

printUser({ id: 7, name: "Nadia" });
console.log(featureFlags.darkMode);

Excess Property Checks on Object Literals

When you pass an object literal directly into a function or typed variable, TypeScript rejects unknown extra properties to catch typos like { nmae: "Nadia" }.

Common Mistakes to Avoid

  • Using lowercase object or {} as a type: {} accepts almost every non-null value (even numbers and strings!), and object blocks reading any properties; always specify exact fields or Record<string, unknown>.
  • Reading optional fields without checking undefined: With "strictNullChecks": true, user.nickname.toUpperCase() errors unless you guard with ?. or ??.
  • Mutating readonly properties via aliases: readonly stops reassignment on that type view, though another non-readonly reference could still mutate it.

Frequently Asked Questions

What is the difference between Record<string, number> and { [key: string]: number }?

They behave identically in most cases. Record<K, V> is shorter and also accepts union keys like Record<"dev" | "prod", string>, which index signatures cannot express directly.

Can an optional property accept undefined explicitly?

By default nickname?: string means string | undefined. If "exactOptionalPropertyTypes": true is enabled, { nickname: undefined } is disallowed unless written string | undefined.

How do I make all properties of an object optional or readonly?

Use built-in utility types Partial<T> or Readonly<T> instead of duplicating the type definition.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum