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:
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.
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.
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.
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:
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);longest.ts:7:9 - error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
7 longest(10, 20);
~~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:
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');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:
| Type | What 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 |
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 } MousePartial for updates (only the changed properties), Omit<Product, 'id'> for a new product (the database assigns the id), and Pick for a small card.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. Tis usually inferred from the argument; when needed, it is written explicitly:first<boolean>([]).T extends Xconstrains a type parameter;K extends keyof Tallows only existing keys.Partial,Pick,Omit,RecordandReturnTypebuild new types from existing ones.- If a type parameter doesn't link at least two places, you don't need a generic.