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.
Thanks a lot. That was a really good explanation which instantly made me understand generics. In fact, I think this is an awesome way to learn new languages and concepts. You start with an example in a language you know and reason about the functionality from that.
- 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:
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.