TypeScript Course
TypeScript
/
Beginner

Object Types

Definition

Defining the shape of a JavaScript object by specifying the names and types of its properties.

Explain Like I'm New

An Object Type is a blueprint. If you are building a 'User' object, the blueprint dictates that it MUST have a name that is a string, and an age that is a number. If you try to add 'wingspan', the inspector rejects it.

Real World Example

Typing a React Component's props object or the shape of a JSON response from an API.

Common Use Cases

  • •Defining data structures
  • •Type checking API responses

Interactive Example

// Inline object typing (Good for small objects)
function printLocation(pt: { x: number; y: number }) {
  console.log(`The coordinates are X: ${pt.x}, Y: ${pt.y}`);
}

// Using a Type Alias (Better for reuse)
type User = {
  id: number;
  name: string;
};

const currentUser: User = {
  id: 1,
  name: "Alice"
};

// ERROR: Object literal may only specify known properties
// const badUser: User = { id: 2, name: "Bob", admin: true };

Interview Questions

basic

  • How do you define the type of an object directly inline?

intermediate

  • What is excess property checking?

advanced

  • What is the difference between `{}` and `object` and `Object`?

Flash Cards

Question

What is excess property checking?

Click to reveal answer
Answer

If you define an object literal directly in an assignment (e.g., `const u: User = { name: 'A', age: 10, fake: true }`), TS strictly rejects `fake` because it wasn't in the type. But if you assign it to an intermediate variable first, TS allows the excess property!

Question

Difference between {}, object, and Object?

Click to reveal answer
Answer

`object` means any non-primitive type (arrays, functions, objects). `{}` means an object with no known properties. `Object` is the global JS object (avoid using this).