When working with JavaScript, we do not have traditional classes. Instead, we use plain objects that have prototype functionality, similar to "hash-tables". Functions in JavaScript are treated as objects, with some added syntax sugar on top.
Although this explanation is not entirely academic and omits certain details, you can explore the concept further by trying out the example below in a browser's debugger:
var parent = {
method1: function() { return 1 } ,
method2: function() { return 2 }
}
var child = Object.create(parent)
child.method2 = function() { return '2a' }
// More examples and explanations provided in the original text.
In ES2015, classes were introduced to simplify object-oriented programming in JavaScript by abstracting away some of the complexity involved in working with objects and prototypes.
Turning our attention back to TypeScript...
var a : { b : string }
a.b = '4'
The notation { b : string }
in TypeScript serves as a type annotation for variables and does not impact the generated JavaScript code directly. When using interfaces or type annotations, no additional code is added to the final JS output.
However, when utilizing class
, TypeScript generates both concrete JS code (prototype object) and adds elements to the type realm for assistance and linting purposes.
In conclusion, there is no significant issue with either approach, but favoring interfaces over classes aligns more closely with common JavaScript coding practices. Some schools of thought even discourage heavy reliance on classes in favor of alternative patterns.