I am new to typescript and I am trying to wrap my head around how generics work. I am wondering why the following code doesn't fly:
function identity<T>(arg: T): T {
let num: number = 2;
return num;
}
let output = identity<number>(1);
I get the error: Type 'number' is not assignable to type 'T'. If the input to the function is a number, does this not mean that the return type of number should work as well, since we are saying that T is of type number?
Tis not going to necessarily be a number. You might have, for exampleidentity<string>("hello")in which casereturn numwould be wrong. You've put nothing to ensure thatTis in any way related tonumber, so TS will fail compiling this as it cannot guarantee the compatibility. - VLAZ