How do you implement a generic function that infers its return type based on its input parameter in TypeScript?

Instruction: Provide an example of a generic function that takes an argument and returns a value of the same type as the argument.

Context: Evaluates the candidate's ability to express the input/output relationship with a generic function and demonstrate inferred type arguments.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

Use a type parameter to relate the argument and result. The compiler can infer it from the argument; callers do not have to supply an explicit type argument.

```typescript function identity(value: T): T { return value; } const text = identity('hello'); const number = identity(42); const original = { id: 7, active: true }; const...

Related Questions