What is the main benefit of writing
function identity<T>(x: T): T { return x; } instead of function identity(x: any): any { return x; }?- aThe generic version runs faster at runtime
- bThe generic version preserves the input's specific type in the return value✓
- cThe generic version allows any type to be passed without restriction, exactly like
any - dThe generic version is only needed for class methods, not plain functions
Explanation:With
any, the function's return type is always any — TypeScript loses track of what was actually passed in, so identity(5) + 1 and identity(5).toUpperCase() both type-check with no error. With T, the compiler captures the actual argument's type and returns that same type, so calling identity(5) gives back number, letting the compiler catch identity(5).toUpperCase() as an error.