Reputation: 83
As I am reading through the documentation, I read that generics are like functions which take in a type and can be extended to fine tune their use.
function add<T>(sum : T, num:T): T {
return sum + num
}
const res = add<number>(1,2)
The following code snippet gives an error saying,
Operator '+' cannot be applied to types 'T' and 'T'.
And I am trying to wrap my head around why that is giving an error.
is giving the explicit types the only solution, like below? example -
function add(sum:number, num:number):number {
return sum + num
}
const res = add(1,2)
Upvotes: 0
Views: 53
Reputation: 2732
Because the generic variable T
can implicitly be of any type; an object
, boolean
, null
, undefined
etc. using the +
operator on it may not valid. Hence you will unfortunately have to be more specific with your types in this situation and only allow ones that can be added e.g. string | number
.
Upvotes: 2