While JavaScript is a dynamically typed language and TypeScript acts as a development-level superset of it, the concept of interfaces in TypeScript differs from those in Dart. In TypeScript, interfaces serve as a blueprint for JavaScript objects to follow at compile time, rather than as strict contracts. This means that errors are caught during compilation if the object does not adhere to the interface.
On the other hand, Dart, being strongly-typed, enforces interfaces with class definitions, creating rigid contracts. In Dart, classes must explicitly implement interfaces before they can be used.
// business_logic.dart
abstract class IItem {
String item;
}
abstract class IRepository {
Future<void> addItem(IItem item);
}
class BusinessLogic {
Repository _repo;
BusinessLogic(this._repo);
void doSomething() async {}
}
In Dart, interfaces are defined using abstract classes, denoted by names starting with "I". The implementation process involves defining separate classes that conform to these interfaces, wherein syntactic differences come into play.
// repo.dart
class Item implements IItem {
String item;
}
class Repository implements IRepository {
Future<void> addItem(IItem item) async {
/* impl */
}
}
Similarly, Dart requires explicit implementation of interfaces through classes like Item
and Repository
. Once again, syntactic variations come into play, emphasizing the necessity of adherence to interface specifications.
(It's worth noting that in TypeScript, there may be instances where the code references structures instead of actual interfaces, potentially leading to errors. Unlike Dart's strong typing system, such issues might go unnoticed until runtime.)
// runtime.dart
import './business_logic' show BusinessLogic;
import './repo' show Repository;
final logic = BusinessLogic(Repository());
The final step involves bringing everything together in runtime. Syntax remains key here, with mentions of selective imports reflecting similarities between TypeScript and Dart, even though Dart doesn't require the same level of specificity.