← कोर्स पर वापस जाएँ: TypeScript from scratch

Generics: generic functions

वीडियो जल्द आ रहा है

Generics are the topic that intimidates beginners most, yet the idea is simple: write code that works with many types without losing information about them. Imagine a function that returns the first element of an array. If you type it with number[], it only works for numbers. If you use any[], it works for everything, but the result is any and you lose safety. You need a way to say: I receive an array of some type and return an element of that same type. That is a generic.

A type parameter

A type parameter is declared between angle brackets before the parentheses: function first<T>(items: T[]). The letter T is an arbitrary name, a kind of variable, but for types. By convention T is used, and U or K for others. When you call the function, TypeScript discovers what T is by looking at the arguments: if you pass a number[], T is number and the return is number | undefined. You almost never have to write it yourself; it is inferred.

typescript
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const a = first([10, 20, 30]);      // number | undefined
const b = first(['x', 'y']);        // string | undefined
const c = first<boolean>([true]);   // explicit, rarely needed

function identity<T>(value: T): T {
  return value;
}

const n = identity(42);       // 42 (literal), type number
const s = identity('hello');  // string
console.log(a, b, c, n, s);

Several type parameters

A function can have more than one type parameter when it relates different types. A function pair<A, B>(a, b) returns the tuple [A, B]; your own map function receives an array of T and a function from T to U, and returns an array of U. Notice how the types flow: the compiler deduces U from what your callback returns, so the result ends up perfectly typed without writing a single type in the call.

typescript
function pair<A, B>(a: A, b: B): [A, B] {
  return [a, b];
}

function mapItems<T, U>(items: T[], transform: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of items) {
    result.push(transform(item));
  }
  return result;
}

const p = pair('age', 30);                          // [string, number]
const lengths = mapItems(['a', 'bb', 'ccc'], (s) => s.length); // number[]
const labels = mapItems([1, 2], (n) => 'item ' + n);          // string[]
console.log(p, lengths, labels);

Arrow functions can also be generic. In .ts files you write const wrap = <T,>(v: T) => [v], and the comma after T helps in .tsx files so it is not confused with a JSX tag. The array methods you already use, such as map, filter and reduce, are defined with generics; that is why their results keep the type. Now you can read their signatures in the documentation.

One last detail about generic inference: if the arguments have different types for the same T, the compiler picks the one that fits best or fails with an error. For example, a function compare<T>(a: T, b: T) called with a number and a string does not compile. You can force the type by writing it, compare<string | number>(1, 'a'), but usually the error is a useful hint that your design called for something else. Learn to read those messages: they usually say which T was inferred and why the other argument does not fit.

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →