Interfaces vs Classes in Typescript: When should you use one over the other?

I don’t understand the concept behind interfaces. When should you be using them over classes?

Have you read this by @Jeff_Mott yet? It may be of some help.

1 Like

I haven’t yet. Thank you.

You can’t instantiate interfaces; instead they’re used to assert that a class (or any object for that matter) has a certain structure. This can be done either when defining the class using implements, or when assigning a class instance to a variable or passing it as parameter:

interface Foo {
  value: string
}

// This is not possible at all
const myFoo = new Foo()

// This will yield an error immediately 
// since value is not a string
class Bar implements Foo {
  value: 42
}

// This is okay...
class Baz {
  value: 42
}

// ... but this will again yield an error,
// since myBaz doesn't match the Foo interface
const myBaz: Foo = new Baz()

Edit: The article provided by @Mittineague is certainly worth reading, but it doesn’t seem to be about typescript… and JS itself doesn’t have interfaces as a language construct. You may refer to the official docs though.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.