Skip to content

Generic Functions

The Course
•
25 min study

Consider a helper that returns the first item of a list. Writing one version for strings and another for numbers repeats the same algorithm. Returning any would lose useful checking: the caller could treat a number as a string. A generic describes the relationship without choosing one fixed element type.

In function first<T>(items: readonly T[]): T | undefined, T is a type parameter. For each call, the checker chooses an element type and uses it consistently for the input and return. Given string[], the return is string | undefined. Given number[], it is number | undefined. T is not a runtime value and cannot be printed.

The caller usually does not need to write angle brackets. Inference can determine T from the arguments. Use an explicit type argument when it adds clarity or when there is not enough information, such as first<string>([]).

Generics preserve a useful relationship; they do not add capabilities. A function with unconstrained T cannot assume every item has a title or can be multiplied. It can safely return or store the item because that does not depend on its particular shape.

Use a generic only when multiple types share an algorithm and preserving the type relationship helps the caller. A domain function that only accepts sessions can simply accept Session. Fewer abstractions are often easier to understand.

Predict, check, then run

Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.

Predict, then runTypeScript
function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}

console.log(first([10, 20]) ?? 0);

const topic = first(["Types", "Arrays"]);

console.log(topic?.toUpperCase() ?? "Empty");
console.log(first<string>([]) ?? "Empty");

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
10
TYPES
Empty

Read a real compiler error

The generic relationship is useful, but the return promises more than an arbitrary list can guarantee.

Find and fix the type errorTypeScript
function first<T>(items: readonly T[]): T {
  return items[0];
}

console.log(first([10]));

Enable JavaScript to edit and type-check this example.

Check your diagnosis

An indexed lookup may be undefined. Return T | undefined and let the caller handle absence. Do not claim the array is nonempty merely because the sample input is.

Preserve a relationship instead of returning any

A generic parameter connects positions in a contract. The function does not know which concrete T a caller chooses, so it can only perform operations justified for every T. Returning, storing or selecting an element can preserve T without assuming its fields.

A missing element is still missing after adding generics. Include undefined when the algorithm can select nothing. The useful achievement is preserving the caller's element type on success, not pretending that every call succeeds.

Preserve a relationship instead of returning any: traceTypeScript
function last<T>(values: readonly T[]): T | undefined {
  return values[values.length - 1];
}

console.log(last([10, 20]) ?? 0);
console.log(last(["Types", "Arrays"]) ?? "Empty");
console.log(last<string>([]) ?? "Empty");

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
20
Arrays
Empty

One algorithm preserves number or string depending on the input. The empty-list branch is explicit, so callers must decide how to display absence.

Preserve a relationship instead of returning any: contrastTypeScript
function identity<T>(value: T): T {
  return value;
}

const book = identity({ title: "Types", pages: 120 });

console.log(book.title);
console.log(book.pages + 1);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types
121

Inference retains the record’s fields. Replacing T with unknown would lose safe access, while any would abandon checking. T preserves a concrete relationship without requiring the helper to inspect the record.

Try the rule on new inputs

Use the selection helper with booleans and records. Then try adding a title access inside an unconstrained helper and explain why only a constraint—not a cast—can justify it.

Debug a plausible mistake

Exercise

Repair the retained element type

The helper must preserve the caller's element type and report possible empty input. Print 25 and Read from separate calls. Add an empty-input check and verify its result is undefined.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
function first<T>(values: readonly T[]): string | undefined {
  return values[0];
}

console.log(first([25]));
console.log(first(["Read"]));

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The type parameter connects the array element and return value; it is not always string.

Hint 2: a first step

Return T or undefined, keeping the element relationship rather than widening to any.

Show one solution
TypeScript
function first<T>(values: readonly T[]): T | undefined {
  return values[0];
}

console.log(first([25]));
console.log(first(["Read"]));
console.log(first([]) === undefined);
Text
25
Read
true

Returning values[0] as string | undefined failed with TS2322 because T could be number, as in the first call. Using T in the return type says "the same type as the elements", so first([25]) is number | undefined and first(["Read"]) is string | undefined. The third call shows the | undefined is not just caution: an empty list really has no first element.

Your turn

Exercise

Generic Functions: practice

last made every caller deal with undefined. Write lastOr, which takes a list and a fallback of the same type and always returns a value: the last item, or the fallback when the list is empty. Print 31 for lastOr([10, 20, 30], 0) + 1, ARRAYS for the uppercased result on ["Types", "Arrays"], and Empty for an empty string list with fallback "Empty". Then predict what lastOr(["Types"], 0) does.

Your workspaceTypeScript
// One type parameter must link the list, the fallback and the result.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

T can appear in more than one parameter. Using it for both the elements and the fallback means the result type needs no | undefined.

Hint 2: a first step

Read the last item into a local variable (its type includes undefined), then choose between it and the fallback.

Show one solution
One possible solutionTypeScript
function lastOr<T>(items: readonly T[], fallback: T): T {
  const item = items[items.length - 1];
  return item === undefined ? fallback : item;
}

const noTopics: string[] = [];

console.log(lastOr([10, 20, 30], 0) + 1);
console.log(lastOr(["Types", "Arrays"], "Empty").toUpperCase());
console.log(lastOr(noTopics, "Empty"));

Enable JavaScript to edit and type-check this example.

Text
31
ARRAYS
Empty

Inside the function item is T | undefined; the === undefined check narrows it, so both branches return a T and the signature can promise T. That is why + 1 and .toUpperCase() need no ??. Because the fallback shares T with the list, lastOr(["Types"], 0) is rejected with TS2345: a number cannot stand in for a missing string.

Change it and explain it

Try calling toUpperCase on the result of last([10, 20]) and read the error. Explain what information any would have lost. Then write down why the return type includes undefined even when one demonstration list happens to be nonempty.

Was this article helpful?

Your response is saved on this device.