function addKey(input, key, value) { input[key] = value; return input; }
this will work on either Objects or on an Array. But if you have static typing and no generics to make it work you have to either:- create two versions of the same function, one for Objects, 2nd for Arrays
- use any as a type of input - this will work, but you will loose most of the benefits of type checking, e.g. you will be also able to pass Number as an input and compiler won't complain, it will be detected as error only on runtime and other things (your function will also return any so further on in the program you won't know what type is used).
With generic it's easy, you write the function once and when you call it you tell what types are used:
// definition:
function addKey<X,Y,Z>(input:X, key:Y, value:Z):X { ... }
// call:
var a = addKey<Array<string>,Number,string>([],0,"fubar");
With this particular example there are probably other ways as well (sum types, common interface) and also compiler may actually detect passing Number as an error (depends how smart it is), but there are more complex cases, where lack of generics will lead to a lot of copy/pasting and boilerplate.Array<double> means the only element you will encounter is a double.
Array<ISomeInterface> means the only element you will encounter is of type ISomeInterface.
hence, you can express part of some code's requirements via the types that a function,class exposes and/or requires.
these requirements can then be checked at compile time.
without this you have to defer the "checking" to runtime.