Home > other >  Why is this code written with TypeScript generics not correct?
Why is this code written with TypeScript generics not correct?

Time:04-14

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)

CodePudding user response:

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.

  • Related