interface is when you just want to describe the shape of an object. There is no code generation for interfaces - they are the only artifact in the type system. You will not see a difference in the generation of code for a class, depending on whether it has an implements clause.
declare class intended to describe an existing class (usually a TypeScript class, but not always) that will be externally present (for example, you have two .ts files that compile to two. js and both are included via script tags on the web page). If you inherit from class using extends (regardless of whether the base type was declare class or a regular class ), the compiler must generate all the code in order to connect the prototype of the chain and the transfer of constructors and not.
If you try to inherit from the declare class , which was supposed to be an interface, you will have a runtime error, because this generated code will reference the object without showing the runtime.
Conversely, if you simply implement interface that was supposed to be a declare class , you will have to re-implement all the members yourself and will not take advantage of code reuse from a potential base class and functions that check the prototype chain at runtime will reject your object since it is not actually an instance of the base class.
To get really stubborn, if you have C ++ background, you can roughly think of an interface as a typedef and declare class as a declaration of an extern constructor that is severely lacking in the definition in this compiled block.
From the clean side of consumption (writing imperative code, not adding new types), the only difference between the interface and declare class is that you cannot have a new interface. However, if you intend to use extend / implement one of these types in the new class , you absolutely must choose the right one between interface and declare class . Only one of them will work.
Two rules that will help you well:
- Is the type alignment name with a constructor function (something invokable with
new ) that is really present at runtime (for example, Date is, but JQueryStatic not)? If not, you definitely want an interface - Am I dealing with a compiled class from another TypeScript file or something similar enough? If yes, use
declare class
Ryan Cavanaugh Jan 15 '13 at 22:27 2013-01-15 22:27
source share