JS Built-ins
TypeScriptbeginner

Generics β€” identity<T>

πŸ“– Usage Example
function identity<T>(x: T): T { return x }
identity(42)        // β†’ 42
identity('hello')   // β†’ 'hello'

The identity function is the simplest generic β€” it preserves the type of its input.

Generics: The Identity Function

The simplest generic function is identity β€” it accepts a value of any type and returns it unchanged.
<T> declares a type parameter that TypeScript infers from the argument.

Challenge: Implement identity<T>(x: T): T.

identity(42)       // β†’ 42
identity('hello') // β†’ 'hello'
πŸ’‘ Hints (1)
  • β€’ The simplest generic function β€” just return what you receive.