I can do this:
enum DogsKinds {
Labrador,
Aski
}
class Dog {
name: string;
kind: DogKinds;
constructor() {}
}
And then init a dog object:
const dog = new Dog();
However I can do the same with interface:
interface Dog {
name: string;
kind: DogsKind;
}
const dog: Dog = {
name: 'some name',
kind: DogsKinds.Labrador
}
And get the same result - easier.
What are the differences, when to use interface and when to use classes, is there a best practice or rule of thumb?
It seems that interfaces are easier to work with, if I wrong please correct me.
I think one important difference is finding out at runtime which kind of object you are dealing with when using inheritance.
With classes you can use the instanceof operator:
if (animal instanceof Dog) { /* ... */ }
When you are just using plain objects with TypeScript you will have to supply an additional property to differentiate the types during runtime.
type AnimalType = 'dog' | 'cat'
interface Dog extends Animal {
type: 'dog'
name: string;
kind: DogsKind;
}
if (animal.type === 'dog') { /* ... */ }