4 ms·
> You don't actually care that it's a Dog BTW, just that it has a method called Bark(), if that's what you call on it. This is exactly where TypeScript helps.
by chanon 14y ago
> You don't actually care that it's a Dog BTW, just that it has a method called Bark(), if that's what you call on it.
This is exactly where TypeScript helps.
With the way TypeScript interfaces work, you can define an interface
interface Barker {
Bark();
}
And have an array of Barkers where each object's class doesn't have to explicitly say that it implements Barker. Ex.
class Dog {
Bark() {console.log('woof');}
}
class Cat {
Meow() {console.log('meow');}
}
var barkers: Barker[]; // array of Barkers
barkers.push(new Dog()); // compiles
barkers.push(new Cat()); // won't compile
Here Dog doesn't have to explicitly declare that it implements Barker. The TypeScript compiler automatically verifies that it does by the fact that it has a Bark() method.
In TypeScript, Arrays already support this level of type checking. With generics, the static type checking will be able to cover a lot more code so that you don't have to depend on writing tests.
- SideburnsOfDoom 14y agoI use interfaces all the time, and like generics, they are a way of getting around the limitations of a strict type system, at the cost of making the type system more complex. I may as well say "Interfaces are an epicycle that IMHO sits poorly with JavaScript." There are good things about strong typing, but it's astonishing how many language constructs can be thrown away if you don't have it.
- AndrewDucker 14y agoWell, yes. You lose huge amounts if you don't have strong typing. After all, "naturally", nothing is strongly typed. Typing was added to languages so that you would have guarantees about what form your data would take.