DEV3 Technologies home

DEV3 Developer Forum

Should I use type or interface in TypeScript?

JavaScript helpSolved0 views
dev3 ·

Both seem to describe object shapes. Is there a real difference, and which should I pick in a new project?

#typescript#types#interface

0

1 reply

dev3 · Accepted answer

For plain object shapes they are almost interchangeable. Differences that matter:

interface

  • Can be merged by redeclaration (declaration merging), useful for augmenting libraries:
interface Window { myAnalytics: Analytics }
  • Extends with extends, and error messages are often clearer.
  • Only describes object-like shapes (and classes can implements it).

type alias

  • Can name anything: unions, intersections, tuples, primitives, mapped and conditional types.
type ID = string | number;
type Pair = [string, number];
type Status = 'idle' | 'loading' | 'error';
type Keys = keyof User;
type Readonly2<T> = { readonly [K in keyof T]: T[K] };
  • Cannot be reopened; duplicate names are an error.
  • Combine with &.

Quick guidance

  1. Use interface for public object contracts and class shapes, particularly in libraries (users can extend it).
  2. Use type for unions, tuples, utility/mapped types and function types.
  3. Be consistent within a codebase; many teams simply use type everywhere, others follow "interface until you need type".

Performance

interface extends is cached by the compiler and can be faster than big intersections of type aliases in very large codebases.

Not just that

Prefer string-literal unions over enum for simple cases; they have no runtime output:

const roles = ['admin', 'editor', 'viewer'] as const;
type Role = typeof roles[number];

Pitfall: using object or {} as a type accepts almost anything. Use Record<string, unknown> for dictionaries.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.