What’s the difference between “declare class” and “interface” in TypeScript

interface is for when you simply want to describe the shape of an object. There’s no code generation, ever, for interfaces — they’re solely an artifact in the type system. You’ll see no difference in the code generation for a class depending on whether or not it has an implements clause.

declare class is for when you want to describe an existing class (usually a TypeScript class, but not always) that is going to be externally present (for example, you have two .ts files that compile to two .js files and both are included via script tags in a webpage). If you inherit from a class using extends (regardless of whether the base type was a declare class or a regular class) the compiler is going to generate all the code to hook up the prototype chain and forwarding constructors and what not.

If you try to inherit from a declare class that should have been an interface, you are going to have a runtime error because that generated code will be referring to an object with no runtime manifestation.

Conversely, if you simply implement an interface that should have been a declare class, you’re going to have to re-implement all the members yourself and won’t be taking advantage of any code re-use from the would-be base class, and functions that check the prototype chain at runtime will reject your object as not actually being an instance of the base class.

To get really nerdy, if you have a C++ background, you can roughly think of interface as typedef and declare class as an extern declaration of a constructor that strictly lacks a definition in this compile unit.

From a pure consumption side (writing imperative code, not adding new types), the only difference between interface and declare class is that you can’t new an interface. However, if you intend to extend/implement one of these types in a new class, you absolutely have to have chosen correctly between interface and declare class. Only one of them will work.

Two rules that will serve you well:

  • Is the name of the type aligning with a constructor function (something invokable with new) that’s actually present at runtime (e.g. Date is, but JQueryStatic is not)? If no, you definitely want interface
  • Am I dealing with a compiled class from another TypeScript file, or something sufficiently similar? If yes, use declare class

Leave a Comment

tech