Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 96 ยท Basic Types

Interfaces

Learn TypeScript interfaces - optional and readonly members, method signatures, extending interfaces, declaration merging and when to choose interface or type.

An interface gives a name to the shape of an object. It lists the properties an object must have, the type of each one, and the methods it can call. Once you have a name like User or Product, you can use it in parameters, return types, arrays and other types, and TypeScript checks every object against it.

You have already met inline object types in Object Types and named shapes with type in Type Aliases. Interfaces cover much of the same ground, but they add two things aliases don't have: a dedicated extends syntax for building shapes from other shapes, and declaration merging, which lets several declarations of the same interface combine into one. This lesson shows both, and ends with a practical rule for choosing between interface and type.

Declaring an interface

The syntax looks like an object type with a name in front. Members are separated by semicolons (commas also work, but semicolons are the common style):

TypeScript A first interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two things are worth noticing in the output and the code:

  • greet(fromForm) compiles even though fromForm has an extra source property. TypeScript is structural: an object fits an interface if it has at least the required members with the right types. The interface name doesn't have to appear anywhere on the object.
  • The interface vanished at runtime. It only exists for the type checker, exactly like the types you saw in How TypeScript Works. The JavaScript that runs is just the objects and the function.

The extra property was fine because fromForm is a variable. If you write the object literal directly where a User is expected, the excess property check from Object Types kicks in and flags source as a probable typo.

Optional and readonly members

Mark a member optional with ? and protect it from reassignment with readonly. Both work exactly as they do in inline object types:

TypeScript Optional and readonly members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Under strict mode, product.description has the type string | undefined, so you can't call string methods on it without handling undefined first. The ?? and ?. operators are the shortest way to do that.

Now try to change the readonly member. This example fails on purpose, so nothing runs and you only see the compiler's message:

TypeScript Assigning to a readonly member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(7,6): error TS2540: Cannot assign to 'sku' because it is a read-only property. Line 7, column 6 points at sku in lamp.sku. Remember that readonly is a compile-time rule only: the property is still writable in the emitted JavaScript, and it says nothing about the contents of the value. A readonly tags: string[] can't be replaced, but you can still push into it unless you also make the array type readonly string[]. Readonly and Immutability covers deep immutability.

Methods in interfaces

An interface can describe functions that live on the object. There are two ways to write them:

TypeScript
interface Counter {
  count: number;
  increment(by?: number): void;     // method syntax
  reset: () => void;                // property syntax (a property holding a function)
}

Both describe something you call as counter.increment(). Method syntax reads more naturally and is the usual choice. The one real difference shows up with strictFunctionTypes: function-typed properties get stricter parameter checks than methods, which are checked "bivariantly" for historical reasons. You'll see why that matters in Type Compatibility and Variance; for now, either style is fine.

TypeScript An object with methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that increment(by = 1) has no annotation on by. Because the returned object is checked against Counter, TypeScript gives the parameter its type from the interface (contextual typing, introduced in Type Inference). Inside the methods, this is the object itself, so this.count is a number. Typing this explicitly is covered in this, Parameter Destructuring and Type Predicates.

Interfaces can also have index signatures ([key: string]: number) for dictionary-like objects, and call signatures for callable values. Those have their own lessons: Index Signatures and Record and Function Types and Callbacks.

Extending interfaces

extends builds a new interface from one or more existing ones. The new interface has every member of its parents plus its own:

TypeScript Building shapes with extends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A few rules about extends:

  • You can extend several interfaces at once, separated by commas, as Customer does.
  • An interface can extend a type alias too, as long as the alias describes an object type (not a union).
  • A child may narrow an inherited member to a more specific type (for example status: string becomes status: 'active' | 'closed'), but it can't change it to an incompatible type. Trying to turn id: number into id: string gives error TS2430, "Interface 'X' incorrectly extends interface 'Y'".

This is the main ergonomic advantage of interfaces: when two parents disagree, you get a clear error at the declaration, instead of a silently impossible type.

Declaration merging

If you declare the same interface name twice in the same scope, TypeScript merges the declarations into one interface with all the members. A type alias can never do this; declaring the same alias twice is an error.

TypeScript Two declarations become one interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You'll rarely merge interfaces inside your own code on purpose. Merging exists mostly for extending types you don't own. Libraries and the built-in type definitions use it so that you, or a plugin, can add members later. For example, a test library can add matcher methods to an Assertion interface, and you can add a property to the global Window interface in a browser project. That's called module augmentation and global augmentation, covered in Declaration Files (.d.ts).

Merging also means an accidental name clash doesn't produce an error. If you write interface Event { ... } in a file that is not a module, it merges with the global Event interface from the DOM library. Our editor runs every file as an ES module, so names stay local, but in older script-style projects pick specific names, or use modules.

When two merged declarations both have a property with the same name, the types must be identical, otherwise you get error TS2717. Methods with the same name are allowed and become overloads (see Function Overloads).

Interface vs type alias

Interfaces and type aliases overlap a lot. For a plain object shape, these two lines are equivalent in almost every situation:

TypeScript
interface PointA { x: number; y: number }
type PointB = { x: number; y: number };

The differences are real but small:

interface type
Object shapes Yes Yes
Unions, tuples, primitives, mapped and conditional types No Yes
Extending extends (checked for conflicts) & intersection
Declaration merging Yes No (duplicate name is an error)
Error messages and tooltips Shows the interface name Sometimes expands the full type

Some types can only be written with type, because an interface always describes one object shape:

TypeScript
type Id = number | string;                     // union
type Pair = [string, number];                  // tuple
type Status = 'draft' | 'published';           // literal union
type ReadonlyUser = Readonly<User>;            // computed with a utility type

A simple rule that most teams follow: use interface for object shapes, especially ones that other code may extend or augment (public APIs, models, props), and use type for everything else: unions, tuples, function types and types computed from other types. Whichever you choose, be consistent in a codebase.

extends vs intersections

type aliases combine shapes with & (intersection types, covered in Object Types in Depth). For compatible members the result is the same as extends. The difference is how conflicts are handled. Here the two parents disagree about id:

TypeScript Conflicting members with extends (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The interface version is rejected right at the declaration with:

TEXT
main.ts(5,11): error TS2430: Interface 'Ticket' incorrectly extends interface 'HasNumericId'.
  Types of property 'id' are incompatible.
    Type 'string' is not assignable to type 'number'.

With an intersection, HasNumericId & { id: string } is accepted silently, and id becomes number & string, which is never. You only discover the problem later, when no value can be assigned. That early, readable error is another reason to prefer extends for object hierarchies. The type checker also caches interface relationships, so large codebases with many extends chains check slightly faster than equivalent intersections.

Interfaces describe, they don't create

An interface never produces a value. You can't write new User() or check x instanceof User; at runtime there is nothing called User. When you need to know at runtime whether some unknown data matches an interface (for example JSON from a server), you write a check yourself. That's a type guard, and you'll write your first one in this, Parameter Destructuring and Type Predicates and many more in Custom Type Guards. If you want a runtime object with a constructor, use a class; classes can implements an interface to promise they have its shape, as you'll see in Classes, Interfaces and Structural Typing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An object has all the members of interface User { id: number; name: string } plus an extra role property, and it is stored in a variable first. Can you pass that variable to function f(u: User)?

    TypeScript is structural. An object that has at least the required members fits the interface. The excess property check only applies to object literals written directly at the place a User is expected.
  2. 2. What happens when you declare interface Settings { a: string } and then interface Settings { b: number } in the same module?

    Interfaces with the same name in the same scope are merged. Declaring the same type alias twice, however, is an error.
  3. 3. Which of these can NOT be written as an interface?

    An interface always describes a single object shape. Unions, tuples and primitive aliases need the type keyword.
  4. 4. Given interface Product { readonly tags: string[] } and const p: Product = { tags: [] }, which line compiles?

    readonly stops you from replacing the property, but the array itself is still a mutable string[]. Use readonly string[] to block push as well.
  5. 5. Why do many teams prefer extends over an intersection (&) for building object types?

    An interface that incorrectly extends its parent fails with error TS2430. An intersection of id number and id string just makes id never, and you find out later.

Summary

  • An interface names an object shape: properties, optional (?) and readonly members, and methods.
  • Interfaces are erased at runtime; checking is structural, so any object with the right members fits.
  • Method syntax (run(): void) and property syntax (run: () => void) both describe callable members; properties get stricter parameter checks.
  • extends combines one or more interfaces and reports conflicting members with error TS2430.
  • Same-named interfaces in one scope merge; this powers library and global augmentation.
  • Use interface for object shapes that may be extended and type for unions, tuples, functions and computed types.

Next: Enums