Middle+
How to make the result type not 'any', but match the argument type using Generics?
sobes.tech AI
Answer from AI
In order for the foo function to accept an argument of type any and return a value of the same type, you need to use Generic types in TypeScript. This allows preserving the argument's type and using it as the result type.
Example:
function foo<T>(arg: T): T {
return arg;
}
// Usage:
const num = foo(123); // type of num: number
const str = foo('hello'); // type of str: string
const obj = foo({a: 1}); // type of obj: { a: number }
Here, T is a type parameter that is inferred from the passed argument, and the function returns a value of the same type.