Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

TypeScript Objects and Interfaces: Shape Your Data Safely

Object Types

Most application data is object-shaped: users, products, posts, settings, API responses, form values, and component props. TypeScript lets you describe those shapes clearly so property names and value types are checked before runtime.

Inline object types are useful for small examples or one-off function parameters. When an object shape is reused or important to the domain, give it a name with an interface or type alias.

Inline Object Type
const user: {
  id: number;
  name: string;
  email?: string;
} = {
  id: 1,
  name: "Kavya",
};

function displayUser(profile: { id: number; name: string }): string {
  return `#${profile.id} ${profile.name}`;
}

Interfaces

An interface gives a reusable name to an object contract. Interfaces are common for models, component props, service inputs, configuration objects, and class contracts.

Interfaces are especially readable when the shape represents a real business concept. A future developer can understand Product faster than a long inline object type repeated in several places.

Interface Model
interface Product {
  readonly id: number;
  name: string;
  price: number;
  tags?: string[];
}

function formatProduct(product: Product): string {
  return `${product.name}: Rs. ${product.price}`;
}

const keyboard: Product = {
  id: 1,
  name: "Keyboard",
  price: 1499,
};

Optional and Readonly Properties

An optional property may be missing. This is useful for values such as profile photos, descriptions, coupon codes, secondary contact details, and draft-only fields.

readonly prevents reassignment through that property. It is useful for IDs, timestamps, and data that should be treated as immutable after creation. It does not deeply freeze every nested object at runtime.

SyntaxMeaningExample
email?: stringProperty may be missingUser profile email
readonly id: numberCannot be reassigned through that propertyDatabase ID
items: string[]Property is requiredCart items
Optional Checks
interface Profile {
  readonly id: number;
  name: string;
  avatarUrl?: string;
}

function getAvatar(profile: Profile): string {
  return profile.avatarUrl ?? "/images/default-avatar.png";
}

const profile: Profile = { id: 1, name: "Asha" };
console.log(getAvatar(profile));

Nested Objects

Real data often contains nested objects. You can write nested shapes inline, but naming nested structures usually makes code easier to read, test, and reuse.

If a nested structure is reused or has its own rules, extract it into a separate interface. This keeps the parent model focused and avoids giant object definitions.

Nested Interface
interface Address {
  city: string;
  country: string;
  postalCode?: string;
}

interface UserProfile {
  id: number;
  name: string;
  address: Address;
}

function formatAddress(profile: UserProfile): string {
  return `${profile.address.city}, ${profile.address.country}`;
}

Methods in Interfaces

Interfaces can describe methods as well as data properties. This is useful for service contracts, repositories, validators, formatters, and objects that expose behavior.

A method signature describes the parameters and return type. Any object with a matching method can be used where the interface is expected.

Interface with Methods
interface UserRepository {
  findById(id: number): Promise<UserProfile | null>;
  save(profile: UserProfile): Promise<void>;
}

async function loadProfile(repo: UserRepository, id: number): Promise<string> {
  const profile = await repo.findById(id);
  return profile ? profile.name : "Unknown user";
}

Extending Interfaces

Interfaces can extend other interfaces. This helps you build a larger shape from smaller concepts without repeating fields.

Use extension when the relationship is natural. If two shapes only happen to share a few fields, a separate type may be clearer than forcing inheritance-like structure.

Interface Extension
interface BaseEntity {
  readonly id: number;
  createdAt: string;
}

interface BlogPost extends BaseEntity {
  title: string;
  slug: string;
  published: boolean;
}

const post: BlogPost = {
  id: 10,
  createdAt: "2026-05-24",
  title: "TypeScript Interfaces",
  slug: "typescript-interfaces",
  published: true,
};

Excess Property Checks

TypeScript checks object literals carefully. If you pass an object literal with a property that the target type does not expect, TypeScript reports it. This catches spelling mistakes and wrong API fields early.

This check is strongest on fresh object literals. If a value is stored in a variable first, TypeScript checks structural compatibility rather than exact property lists.

Extra Property Error
interface Course {
  title: string;
  lessons: number;
}

const course: Course = {
  title: "TypeScript",
  lessons: 15,
  // lessonCount: 15, // Error: unknown property
};

const rawCourse = {
  title: "TypeScript",
  lessons: 15,
  lessonCount: 15,
};

const accepted: Course = rawCourse; // structurally compatible

Interface vs Type Alias

Interfaces and type aliases can both describe object shapes. Interfaces are often preferred for object contracts that may be extended. Type aliases are useful for unions, tuples, primitive aliases, mapped types, and complex compositions.

Many teams use both. The practical rule is simple: use interfaces for object models and service contracts, and use type aliases when you need unions or type transformations.

NeedCommon Choice
Reusable object modelInterface
Component props objectInterface or type alias
Union of string valuesType alias
TupleType alias
Mapped or conditional typeType alias
Key Takeaways
  • Object types describe property names and value types.
  • Interfaces are named object contracts for models, props, services, and class-like behavior.
  • Optional properties may be missing and should be handled before use.
  • Readonly properties protect values from reassignment through that property.
  • Nested interfaces keep larger models readable.
  • Interfaces can include methods and extend other interfaces.
  • Excess property checks catch mistakes in fresh object literals.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.