Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 20946  / 7 Years ago, wed, may 17, 2017, 12:00:00

What is the difference between generic Type(T) vs any in typescript?



Function 1



function identity(arg: any): any {
return arg;
}


Function 2



function identity<T>(arg: T): T {
return arg;
}


Function 3



function identity<T>(arg: T[]): T[] {
return arg;
}






Function 1 & 3 is accepted if we passing any kind of data type, But the function 2 does not accept if we pass an array. generic type is accepting all kind of data type on compile time. but here why it does not accept?




Also which function is good for better performance ( function 1 or function 3)?


More From » angular

 Answers
2

There is no difference if this is identity function that just returns an argument and used without type restrictions:



const foo: any = fn(['whatever']);


And there is a difference for typed code:



const foo: string = fn('ok');
const bar: string = fn([{ not: 'ok' }]);


Also, the usage of generic type provides semantics. This signature suggests that the function is untyped and returns anything:



function fn(arg: any): any { ... }


This signature suggests that the function returns the same type as its argument:



function fn<T>(arg: T): T { ... }


Real functions are usually more meaningful than just return arg example. Generic type can benefit from type restrictions (while any obviously can't):



function fn<T>(arg: T[]): T[] {
return arg.map((v, i) => arg[i - 1]);
}


But the benefits become more obvious when the function is used in conjunction with other generic classes and generic functions (and eliminated if non-generics are involved):



function fn<T>(arg: T[]): T[] {
return Array.from(new Set<T>(arg));
}


This allows to consistently maintain T type between input (argument) and output (returned value):



const foo: string[] = fn(['ok']);
const bar: string[] = fn([{ not: 'ok' }]);


There cannot be any difference in performance because TypeScript types exist only on design time.


[#57758] Monday, May 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kyrona

Total Points: 422
Total Questions: 111
Total Answers: 97

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;