Objects, Arrays, and Interfaces in TypeScript

Learn how TypeScript models objects and arrays, when to use interfaces, and how to type React props while keeping untrusted runtime data safe.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

TypeScript object types describe required and optional fields, while arrays describe collections of values with the same shape. Interfaces give shared object contracts a name, and React prop types catch incompatible data or callbacks during compilation. This post also covers structural compatibility, safe list rendering, and why API responses need runtime validation before components rely on them.

Objects, Arrays, and Interfaces in TypeScript

Introduction

React passes around lists, records, and callbacks. TypeScript describes their shapes so the editor can catch mismatches. Its type system is structural: a value fits when it has the required properties, without inheriting from a class.

This post explains object and array shapes, the relationship between interfaces and aliases, and how those contracts help type React props without replacing runtime validation.

For example, each article has a title and may include a reading time. The array contains only values with that shape:

interface ArticleSummary {
  title: string;
  readMinutes?: number;
}

const articles: ArticleSummary[] = [
  { title: "TypeScript Basics", readMinutes: 8 },
  { title: "React Props" },
];

Interfaces and structural typing

An interface names an object shape and can be extended. A type alias also describes objects and can express unions such as status above. For component props, either works; follow your team’s convention.

Structural typing allows extra fields. Fresh object literals may get an excess-property error for typos, but this is not runtime validation.

Give React props a clear contract

Name the props contract and annotate the component parameter. Handle optional fields instead of assuming they exist.

interface Article {
  slug: string;
  title: string;
  readMinutes?: number;
}

interface ArticleCardProps {
  article: Article;
  onOpen: (slug: string) => void;
}

function ArticleCard({ article, onOpen }: ArticleCardProps) {
  return (
    <button onClick={() => onOpen(article.slug)}>
      {article.title} ({article.readMinutes ?? "unknown"} min)
    </button>
  );
}

This catches a missing slug, a numeric title, or a callback with the wrong argument.

Follow the data flow

flowchart LR
  A[Article data] --> B[Article list]
  B --> C[ArticleCard props]
  C --> D[Rendered button]
  D --> E[onOpen callback]

Production Failure Scenarios

Suppose an API changes readMinutes: 6 to the string "6". Your fixture still passes, but production formatting or arithmetic may fail. TypeScript does not inspect browser JSON. Treat external values as unknown, validate them at the boundary, then pass checked data to components. A schema validator helps with larger payloads.

If an endpoint unexpectedly returns null where the UI expects Article[], a call to .map() can crash the list. Check that the response is an array and validate each item before rendering.

Security and Compliance Notes

A cast like payload as Article is not validation. Sanitize user HTML or URLs for their intended use; TypeScript types do not prevent injection. Keep private payloads out of logs.

Trade-Off Table

Choice Useful when Cost
Inline object type A one-off local value Repeating a shape gets hard to maintain
Interface A named object contract shared by components Adds a name to keep consistent
T[] A list whose items share one shape Does not express a non-empty list
Runtime schema Data crosses an API or storage boundary Adds validation code or a dependency

Common Pitfalls / Anti-Patterns

  • Treating structural typing as proof that a server response is valid; TypeScript checks code, not network payloads.
  • Assuming T[] guarantees at least one item; an empty array is still valid.
  • Repeating inline object shapes across components instead of naming a shared contract.
  • Using any or a type assertion to bypass a mismatch that should be checked at the boundary.

Observability Checklist

  • Record validation failures and the affected endpoint.
  • Track unexpected nulls or empty lists.
  • Include a safe request ID with validation failures; avoid logging full payloads.

When to Use / When NOT to Use

Use an interface for a named object shape shared by components or functions, and use a type alias when you need a union or intersection. Inline an object type for a small, one-off local value.

Do not introduce a named interface for every temporary object. Keep the type near the code when it has one use and no meaningful contract to communicate.

Quick Recap Checklist

  • Use object types to describe required and optional fields.
  • Use T[] for collections and tuples for fixed positions.
  • Use interfaces to name shared object contracts; structural compatibility is based on shape.
  • Type React props, then validate data that comes from outside your TypeScript code.
  • Avoid any and unchecked casts when a value needs inspection.

Interview Questions

1. What does structural typing mean in TypeScript?
A value is compatible when it has the required properties with compatible types. It need not declare that it implements an interface.
2. When would you use an interface instead of an object type inline?
Name a shape with an interface when several components or functions share that contract. Inline types are fine for a small, local value. A type alias is also suitable for object shapes and is needed for unions.
3. Do TypeScript interfaces validate API responses?
No. Type information is removed when TypeScript compiles to JavaScript. Validate external input at runtime, then use the checked value as a trusted application type.
4. What does the optional marker mean on an object property?
A property marked with ? may be missing.
  • Check or provide a fallback before using it.
  • Optional does not mean the value is always present as undefined.
5. Are arrays typed with T[] guaranteed to contain an item?
No. The array can be empty and every element it does contain must match T.
  • Check the length before reading the first element.
  • Use a tuple for a fixed number and order of entries.
6. When is a tuple a better fit than an array?
A tuple fits a small fixed sequence where each position has a known role.
  • For example, a coordinate can be [number, number].
  • Use an array for a variable-length collection of similar values.
7. How can an object with extra properties still match a type?
Structural compatibility checks for required properties with compatible types.
  • A value can have additional fields.
  • Fresh literals may get extra-property checks to catch likely typos.
8. When can an interface extend another interface?
Use extension when one object contract adds fields to a related base contract.
  • It communicates the shared fields and specialization.
  • Use a type alias for unions and other composed type expressions.
9. What does a typed React prop callback describe?
Its function signature describes the arguments the child sends to its parent.
  • (slug: string) => void accepts a string and returns no useful value.
  • Callers with an incompatible callback get a compile-time error.
10. Why can an excess-property check be misleading?
It is a compile-time check for some object literal assignments, not a runtime filter.
  • It does not strip extra fields from JavaScript values.
  • Validate external data explicitly before using it.

Further Reading

Conclusion

Objects and arrays describe React data; interfaces name shared shapes, and typed props catch wiring mistakes. Validate external data at runtime before treating it as trusted.

Category

Related Posts

Nullable and Unknown Data in TypeScript Interfaces

Learn to model optional and nullable fields, narrow unknown values, and safely parse API or storage data in React with strict TypeScript checks.

#typescript #react #interfaces

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility

Advanced React State: When Local State Stops Fitting

Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.

#react #typescript #state-management