Generics and utility types

Write functions and interfaces that work with any type without losing type information, constrain them with `extends` and `keyof`, and build new types with `Partial`, `Pick`, `Omit`, `Record` and `ReturnType`.

  • Advanced
  • 18 min
  • 10 questions
  • Lesson 7 of 8

In this lesson you will learn

  • Write a generic function with a type parameter <T>
  • Describe generic interfaces and types
  • Constrain type parameters with extends and keyof
  • Apply the utility types Partial, Pick, Omit, Record and ReturnType

You need a function that returns the first element of an array: for cities, for prices, for users. Writing separate firstString, firstNumber and firstUser functions makes no sense. And any destroys the type information. The code below compiles without errors, but when it runs it crashes with TypeError: city.toFixed is not a function — the compiler no longer knows that city is a string:

TypeScript
function firstAny(items: any[]): any {
  return items[0];
}

const city = firstAny(['Baku', 'Ganja']);
console.log(city.toFixed(2));

Generic functions

GenericDefinition

A function, interface or class that takes a type as a parameter. The type parameter is written in angle brackets — usually <T> — and is replaced by a concrete type at each use, just as an ordinary parameter is replaced by a concrete value.

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

const city = first(['Baku', 'Ganja']);
const score = first([90, 75]);
const empty = first<boolean>([]);

console.log(city?.toUpperCase(), score?.toFixed(1), empty);

Expected output

BAKU 90.0 undefined
city has the type string | undefined and score has number | undefined. Because the array may be empty, undefined is included too.

Here T means “a type that isn't known yet”. In the call first(['Baku', 'Ganja']), TypeScript looks at the argument and infers by itself that T is string. You can also give the type explicitly: first<boolean>([]). That is useful when TypeScript can't work the type out, as with an empty array.

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

Generic interfaces

A type itself can take a parameter, too. A server always answers in the same shape — a status and some data — but the data differs for every request. Instead of writing a separate interface for each case, we write one generic interface. In fact, you have already used generics: Array<string> and Promise<number> are generic types too.

TypeScript
interface ApiResponse<T> {
  status: number;
  data: T;
}

type User = { id: number; name: string };

const userResponse: ApiResponse<User> = {
  status: 200,
  data: { id: 1, name: 'Leyla' },
};

const tagsResponse: ApiResponse<string[]> = {
  status: 200,
  data: ['typescript', 'generics'],
};

console.log(userResponse.data.name, tagsResponse.data.length);

Expected output

Leyla 2

Constraints: extends and keyof

Sometimes T can't be “any type at all”. A function that returns the longer of two values needs a length property. Writing T extends { length: number } is a constraint: T may only be a type with a length property — a string, an array and so on. Numbers have no length:

TypeScript
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

console.log(longest('Baku', 'Sumgait'));
console.log(longest([1, 2, 3], [4, 5]));
longest(10, 20);
Text
longest.ts:7:9 - error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

7 longest(10, 20);
          ~~
Remove the faulty line and the program prints Sumgait and [ 1, 2, 3 ].

The keyof T operator gives the union of all keys of an object type: for { title: string; year: number } it is 'title' | 'year'. T[K] is the type of the value under that key. Put them together and you get a function that accepts only existing properties and returns exactly the right type:

TypeScript
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const book = { title: 'Ali and Nino', year: 1937 };

const title = getProperty(book, 'title');
const year = getProperty(book, 'year');
console.log(title.toUpperCase(), year + 1);
getProperty(book, 'author');
Text
book.ts:10:19 - error TS2345: Argument of type '"author"' is not assignable to parameter of type '"title" | "year"'.

10 getProperty(book, 'author');
                     ~~~~~~~~
title gets the type string and year gets number. The non-existent key 'author' is rejected.

Utility types

TypeScript comes with ready-made utility types built on generics. They make a new type from an existing one, so you never have to write the same properties twice. These are the ones you will use most:

TypeWhat it does
Partial<T>makes every property optional
Required<T>makes every property required
Readonly<T>makes every property read-only
Pick<T, K>keeps only the chosen properties K
Omit<T, K>keeps everything except the properties K
Record<K, V>an object whose keys are K and values are V
ReturnType<F>the type that the function F returns
TypeScript
interface Product {
  id: number;
  name: string;
  price: number;
  stock: number;
}

const laptop: Product = { id: 1, name: 'Laptop', price: 1500, stock: 4 };

function update(product: Product, changes: Partial<Product>): Product {
  return { ...product, ...changes };
}

type ProductCard = Pick<Product, 'name' | 'price'>;
type NewProduct = Omit<Product, 'id'>;

const card: ProductCard = { name: laptop.name, price: laptop.price };
const draft: NewProduct = { name: 'Mouse', price: 25, stock: 30 };

console.log(update(laptop, { price: 1350 }));
console.log(card, draft.name);

Expected output

{ id: 1, name: 'Laptop', price: 1350, stock: 4 }
{ name: 'Laptop', price: 1500 } Mouse
Partial for updates (only the changed properties), Omit<Product, 'id'> for a new product (the database assigns the id), and Pick for a small card.
TypeScript
type City = 'Baku' | 'Ganja' | 'Shaki';

const deliveryDays: Record<City, number> = {
  Baku: 1,
  Ganja: 2,
  Shaki: 3,
};

function createUser(name: string, age: number) {
  return { name, age, createdAt: '2025-09-01' };
}

type User = ReturnType<typeof createUser>;

const user: User = createUser('Elvin', 16);
console.log(deliveryDays.Ganja, user.name, user.createdAt);

Expected output

2 Elvin 2025-09-01
Record<City, number> requires a value for every city: forget Shaki and you get error TS2741.

Remember

  • A generic takes a type as a parameter: function first<T>(items: T[]): T | undefined.
  • T is usually inferred from the argument; when needed, it is written explicitly: first<boolean>([]).
  • T extends X constrains a type parameter; K extends keyof T allows only existing keys.
  • Partial, Pick, Omit, Record and ReturnType build new types from existing ones.
  • If a type parameter doesn't link at least two places, you don't need a generic.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

10 questions. Every correct answer earns XP.

Question 1 / 10

Question 1 / 10. In function first<T>(items: T[]): T | undefined, what is <T>?