I'm new to programming. and can't understand the difference between the abstract class and typescript interface?
-
In general, there is an expectation from readers that question authors search the site prior to asking a question here. – halfer May 31 '19 at 17:41
2 Answers
One of the main differences is that an interface is just there to tell you the "shape" of your data. An interface generates no JavaScript code at all. See the code vs. the generated JS code here
An abstract class is defined as:
Abstract classes are base classes from which other classes may be derived. They may not be instantiated directly. Unlike an interface, an abstract class may contain implementation details for its members. The abstract keyword is used to define abstract classes as well as abstract methods within an abstract class.
via: https://www.typescriptlang.org/docs/handbook/classes.html
With a regular class, you can create a new
instance of it like this
class MyClass {
constructor() {}
}
var a = new MyClass();
So that means you can't new
an abstract class, you get an error
abstract class MyAbstractClass {
constructor() {}
}
var a = new MyAbstractClass(); //error! "Cannot create an instance of an abstract class.
"
Abstract classes are meant to use as a "base class", like this:
abstract class Animal {
constructor(public legs: number, public sound: string) {
console.log(`I have ${this.legs} legs and I say "${this.sound}"!`)
}
}
class Dog extends Animal {
constructor() {
super(4, 'bark');
}
}
class Cat extends Animal {
constructor() {
super(4, 'meow');
}
}
var a = new Dog();//Logs: I have 4 legs and I say "bark"!
var b = new Cat();//Logs: I have 4 legs and I say "meow"!

- 29,851
- 23
- 95
- 135
Abstract class available at runtime and interface at compile time. For example we cannot use instanceof with interfaces.
let u: any;
var IsExpressionValid = x instanceof IUser; //This will give error.
var IsExpressionValid = x instanceof User; //This will not.

- 272
- 2
- 11