Quantcast
Channel: When to use classes vs. interfaces in a TypeScript library? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Answer by T.J. Crowder for When to use classes vs. interfaces in a TypeScript library?

$
0
0

(From your comment):

I'm asking why they defined them as classes and not interfaces.

There's overlap between type, interface, and class (you clearly know that, but I have to start somewhere :-) ), but class does three things rather than just the one thing that interface or type would do. Let's look at a simpler example:

declare namespace example1 {    class Example1 {        a: string;        constructor(a: string);        static method(): void;    }}

That:

  • Defines the type Example1 which describes instances.
  • Defines that there is a runtime binding, Example1, that refers to the constructor function for those instances. (It doesn't create the binding, it just says there is one.)
  • (Implicitly) Defines a type (typeof Example1) that is the type of the constructor function.

If you wanted to write the same thing without class, you'd have to write each of those three things yourself, such as example2 here:

declare namespace example2 {    // Define the type for instances    interface Example2 {        a: string;    }    // Define that there is a binding for the constructor function    let Example2: {                 //        new (a: string): Example2;  // Define the type for the constructor function        method(): void;             //    };                              //}

You might even go further and declare a named type for the constructor function:

declare namespace example3 {    // Define the type for instances    interface Example3 {        a: string;    }    // Define the type for the constructor function    interface Example3Constructor {        new (a: string): Example3;        method(): void;    }    // Define that there is a binding for the constructor function    let Example3: Example3Constructor;}

(That's what lib.es5.d.ts does for, say, Array, except it uses var instead of let.)

As always when there's more than one way to do something, some folks will do it one way, others will do it another, but there's some argument for using class when it describes all of the parts you're trying to describe at once.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>