1. Home
  2. Blog
  3. Software Development

Software Development

TypeScript Interface vs Type: Real Differences, Tested With the Compiler

Interfaces and type aliases overlap so much that the choice often feels arbitrary. Here is what each can do that the other cannot, confirmed by real compiler errors, plus a simple rule your team can follow.

8 min read
TypeScript interface vs type: real differences, tested with the compiler

Key takeaways

  • For plain object shapes, an interface and a type alias are almost interchangeable.
  • Only type can name unions, tuples and other non-object types.
  • Only interface supports declaration merging, where two declarations combine.
  • A common rule: interfaces for object shapes, type for everything else, applied consistently.

Few TypeScript questions cause as much debate as TypeScript interface vs type. Many articles list differences that used to matter in older versions but are now out of date. So rather than repeating claims, we tested them.

We wrote one file exercising each difference, and checked it with TypeScript 5.6.3 in strict mode. The compiler errors quoted below come from that run. Behaviour can change between versions, so check against the TypeScript version your project uses. If you are new to the language, start with our TypeScript tutorial for beginners.

The short answer

An interface describes the shape of an object, and can be extended or reopened. A type alias gives a name to any type, including objects, unions, tuples and function types. Where both can work, the difference is mostly style.

Where they are the same

These two declarations describe identical shapes:

interface User {
  id: number;
  name: string;
  email?: string;
}

type UserAlias = {
  id: number;
  name: string;
  email?: string;
};

const a: User = { id: 1, name: "Asha" };
const b: UserAlias = a;   // no error

TypeScript uses structural typing, which means it compares shapes rather than names. That is why a User can be assigned to a UserAlias with no complaint. Both support optional properties, readonly properties, methods and index signatures.

Interface vs type side by side

Feature interface type
Object shapes Yes Yes
Unions, such as "a" | "b" No Yes
Tuples and primitives No Yes
Mapped and conditional types No Yes
Declaration merging Yes No, it is an error
Extending extends & intersection
Conflicting properties Error at the declaration Can quietly become never
Used with implements Yes Yes, if it is an object type

What only type can do

Many useful types are not object shapes at all, and only a type alias can name them:

type Status = "pending" | "paid" | "shipped";   // union
type Point = [number, number];                    // tuple
type Handler = (event: string) => void;           // function type
type Keys = keyof User;                           // computed type
type ReadonlyUser = Readonly<User>;               // utility type

Union types are among TypeScript’s most valuable features, because the compiler then rejects any value outside the list:

let s: Status = "paid";
s = "refunded";

// error TS2322: Type '"refunded"' is not assignable to type 'Status'.

This catches typos and outdated values at compile time, before they reach production.

Declaration merging

If you declare an interface with the same name twice, TypeScript merges them into one:

interface Settings {
  theme: string;
}
interface Settings {
  language: string;
}

const settings: Settings = { theme: "dark", language: "en" };   // no error

Try the same thing with a type alias, and the compiler refuses:

type Config = { theme: string };
type Config = { language: string };

// error TS2300: Duplicate identifier 'Config'.

Merging is how libraries let you extend their types. For example, you can add a custom property to the global Window interface, or to a framework’s request object, without modifying the library. That is genuinely useful.

The flip side is that merging can happen by accident. If two files in a project declare an interface with the same name in the same scope, they silently combine, which can be confusing. A type alias makes that collision an error instead.

extends vs intersections

Both let you build on an existing type:

interface Admin extends User {
  permissions: string[];
}

type AdminAlias = UserAlias & { permissions: string[] };

For compatible properties, the result is the same. The difference shows up with a conflict. When an interface tries to change a property’s type incompatibly, the compiler reports it at once:

interface Base { id: number }
interface Broken extends Base { id: string }

// error TS2430: Interface 'Broken' incorrectly extends interface 'Base'.
//   Types of property 'id' are incompatible.
//     Type 'string' is not assignable to type 'number'.

An intersection does not complain when it is declared. Instead, the conflicting property becomes never, a type that no value can have. The error only appears later, when you try to use it:

type Mixed = { id: number } & { id: string };
const m: Mixed = { id: 1 };

// error TS2322: Type 'number' is not assignable to type 'never'.

That later error is more confusing, since it points away from the actual mistake. This is one practical reason to prefer extends when building up object types.

Classes and implements

A class can promise to match a shape using implements, and this works with an interface or an object type alias:

class Account implements User {
  constructor(public id: number, public name: string) {}
}

This compiled without errors. Note that implements only checks that the class matches. It does not add any properties or code. A class cannot implement a union type, since there is no single shape to match.

Readonly and utility types

Utility types such as Readonly, Partial, Pick and Omit work with both interfaces and aliases. The result is a new type, which is typically named with a type alias:

const r: ReadonlyUser = { id: 3, name: "Dev" };
r.name = "Chitra";

// error TS2540: Cannot assign to 'name' because it is a read-only property.

Remember that readonly is a compile-time check only. At run time the object is ordinary JavaScript, and it can still be changed by code that bypasses the types.

Tip: Types disappear when TypeScript compiles to JavaScript. Data that arrives from outside, such as an API response, is not checked at run time just because it has a type. Validate it, for example with a schema library. Our Fetch API tutorial covers handling API responses safely.

Compiler performance

The TypeScript team’s own performance guidance suggests preferring interfaces that use extends over large intersections, because the compiler can cache interface relationships more efficiently. In small and medium projects you are unlikely to notice any difference. It may matter in very large codebases with deeply composed types. We did not measure this ourselves.

Which should you use?

A widely used rule, in line with guidance from the TypeScript handbook, is:

  • Use interface for object shapes, especially public APIs and anything that classes implement or others may extend.
  • Use type for unions, tuples, function types, and mapped or computed types.
You are defining Use
A data model, such as User or Order interface
A set of allowed values type union
A fixed-length pair or triple type tuple
A callback signature type
Extending a library’s types interface, through merging
A variation of an existing type type with a utility type

Some teams simply use type everywhere, and that also works well. What matters most is consistency, so pick a convention, write it in your style guide and let a linter enforce it. ESLint’s consistent-type-definitions rule from typescript-eslint can do this.

Common mistakes

  • Endless debate. Both are fine for objects, so settle the rule once and move on.
  • Accidental merging. Reusing an interface name in the same scope silently combines them.
  • Conflicting intersections. They create never types with confusing errors later.
  • Trusting types at run time. They are erased, so validate external data.
  • Using any to silence errors. It switches off checking. Prefer unknown and narrow it.

Switching between them in an existing codebase

Changing an interface to a type, or the reverse, is usually safe for plain object shapes, because TypeScript compares types by their structure, not by their names. A few things still need checking before you switch:

  • Converting an interface to a type alias removes declaration merging, so any second declaration with the same name becomes a duplicate identifier error.
  • Converting a type alias to an interface only works for object shapes. Unions, tuples and mapped types must stay as type aliases.
  • Error messages and editor hovers may display the type differently, which can surprise teammates but does not change behaviour.

Make the change in one focused pull request, run the compiler in strict mode and your test suite, and avoid mixing it with feature work so reviewers can see that nothing else changed.

Final thoughts

The interface vs type question has a calm answer: they overlap for objects, each has a few unique abilities, and consistency matters more than the choice. Use interfaces for shapes and types for everything else, unless your team prefers otherwise. To see the differences yourself, copy the examples above into a file and run tsc --noEmit --strict on it.

Frequently asked questions

What is the difference between interface and type in TypeScript?

Both can describe object shapes. Only type can name unions, tuples and computed types, while only interface supports declaration merging.

Should I use interface or type for React props?

Either works well. Many teams use interfaces for props, while others prefer type for consistency with unions. Choose one and apply it throughout the project.

Can a type extend an interface?

Yes, by using an intersection such as type Admin = User & { permissions: string[] }. An interface can also extend an object type alias.

Is interface faster than type?

TypeScript’s performance guidance favours interface extends over large intersections in big codebases. In typical projects, the difference is unlikely to be noticeable.

What is declaration merging?

It is when two interfaces with the same name in the same scope combine into one. Type aliases cannot merge, and duplicate names cause an error.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →