If you want strongly typed language support (and I do), then generics make it vastly easier to write maintainable code.
A generic doesn't mean "anything goes" - it means "You will definitely get the thing that you specified".
If you want strongly typed language support (and I do), then generics make it vastly easier to write maintainable code.
A generic doesn't mean "anything goes" - it means "You will definitely get the thing that you specified".
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.
You make sure that your code only puts dog-like objects into the list, either by writing tests or by reading the code and praying. But the system of putting objects into lists is really, really simple.
I see the benefit of strong typing and I use it all the time. Generics are an epicycle that IMHO sits poorly with JavaScript.
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.
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.