I came across this recently where I am not sure whether to use the interface or class to define a particular type.
Note: This question is NOT asking about the difference between a
class
andinterface
For example, given this class and interface
interface IMyClass {
foo: string;
bar: () => string;
}
class MyClass implements IMyClass {
foo = 'foo';
bar() {
return 'bar';
}
}
I would use either the class or interface as the type in a function argument.
Option A - Use class as type
function identityByClass(value: MyClass): MyClass {
return value;
}
Option B - Use interface as type
function identityByInterface(value: IMyClass): IMyClass {
return value;
}
From my point of view, I think either is fine but I prefer to use the class to avoid syncing all methods/properties on the interface. I see the interface as only a template/contract that a class must abide by.
However, most times, in my case, the class often adds more methods/properties that are not on the interface definition.
Case in point, this class below.
class MyClassPlus implements IMyClass {
foo = 'foo';
bar() {
return 'bar';
}
doMore() {
console.log('more stuff here!');
}
}
In which case I could no longer use the two interchangeably.
Any links to best practices would be nice too. Thanks.