Skip to content

QuizNot attempted

Literal inference through an identity generic

What are the types of a, b and c?
function identity<T>(value: T): T { return value; }
const a = identity('hello');
let b = identity('hello');
const c = identity<string>('hello');
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • a: 'hello', b: string, c: string
  • T is inferred as the literal 'hello' (it appears at the top level of the return type, so TS keeps the literal), giving a: 'hello'
  • let widens that widening literal to string so b can be reassigned
  • an explicit <string> skips inference entirely.
  • Not 'all string': inference keeps literal types here.
  • Not 'all hello': let widens and the explicit argument wins.
  • Not b: 'hello': a mutable let binding widens fresh literal types.