Generic identity
Concept and syntax
A type parameter T represents a type chosen at a call site. In identity<T>(x:T):T, the return type relates directly to the input, unlike any which loses that relationship. Inference often chooses T automatically; an explicit type argument can constrain the call.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function identity<T>(x:T):T{return x;}const n:number=identity(7);const s:string=identity("tea");console.log(n,s);Expected output:
7 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
function identity<T>(x:T):T{return x;}identity<number>("7");Expected diagnostic: TS2345. An explicit number argument fixes T to number. Supply a number or choose the correct T.
Practice and recap
Call identity with an object and access an inferred field.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic identity — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function identity<T>(x:T):T{return x;}const n:number=identity(7);const s:string=identity("tea");console.log(n,s);Which diagnostic and explanation match the rejected example under the lesson settings?
function identity<T>(x:T):T{return x;}identity<number>("7");