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.
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
anyor 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
anyand unchecked casts when a value needs inspection.
Interview Questions
? may be missing.
- Check or provide a fallback before using it.
- Optional does not mean the value is always present as
undefined.
T.
- Check the length before reading the first element.
- Use a tuple for a fixed number and order of entries.
- For example, a coordinate can be
[number, number]. - Use an array for a variable-length collection of similar values.
- A value can have additional fields.
- Fresh literals may get extra-property checks to catch likely typos.
- It communicates the shared fields and specialization.
- Use a type alias for unions and other composed type expressions.
(slug: string) => voidaccepts a string and returns no useful value.- Callers with an incompatible callback get a compile-time error.
- It does not strip extra fields from JavaScript values.
- Validate external data explicitly before using it.
Further Reading
- Continue with Type Inference and Annotations to see how TypeScript derives and checks values.
- Union Types and Narrowing shows how to model finite sets of values.
- For component-level examples, read Typed Function Components.
- The TypeScript Handbook’s object types reference covers interfaces and optional properties.
- For React-specific guidance, see the official React TypeScript guide.
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.
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.
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.