Beginner · 10 min
Generic functions
Preserve the relationship between an input type and its result.
Keep the input type
A type parameter lets a function work with different types while keeping useful information. It does not mean that the function can perform every operation on every input.
function identity<T>(value: T): T { return value; }
console.log(identity("Ada").toUpperCase());Output
ADA
Represent a missing result
A generic array function must still account for an empty array. Returning T | undefined lets the caller handle the missing result explicitly.
function first<T>(items: readonly T[]): T | undefined { return items[0]; }
console.log(first<number>([]) ?? 0);Output
0
Put it into practice
- Read the types and predict the output before running the examples.
- Complete the task, then check your understanding with the practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Return the generic input
Make "identity" return its input while preserving type "T". Display the result for "Ada".
Return "value" instead of an unrelated string.