Generics and Types Built from Other Types
Write functions that work for any element type without giving up checking, constrain keys with keyof, and derive new types with typeof, indexed access and utility types.
Contentsand lesson path
On this page
- Why it matters
- Generic functions
- Constraining a generic with keyof
- Types built from values: as const and typeof
- Utility types: new types from old
- Check your understanding
- Apply it
- Review prompt
Lessons of TypeScript Foundations
- Why Types: Annotations, Inference and the Compiler Concept · 20 min
- Modeling Data with Unions, Literals and Interfaces Worked example · 25 min
- Narrowing and Validating Data You Do Not Control Worked example · 25 min
- Generics and Types Built from Other Types Concept · 25 min
- Lab: Convert a JavaScript Module to Strict TypeScript Lab · 30 min
- Check: Type Puzzles and Compiler Errors Knowledge check · 8 questions
What you will learn
- Write generic functions and types, and derive types with keyof, typeof, indexed access and utility types such as Partial, Pick, Omit and Record.
Prerequisites: JavaScript Foundations
01. Why it matters
Sooner or later you write the same function twice with different element types: "highest scoring entry" for courses, then for players, then for products. Copying the function per type does not scale, and the escape hatch — typing the parameter as any — is worse: any loses the link between what goes in and what comes out, so the compiler can no longer check either end. A generic keeps that link. It is a function (or type) with a placeholder, a type parameter, filled in per call. The catalogue module gets two of them in this lesson, and then the toolbox that builds new types from existing ones.
02. Generic functions
maxBy finds the best item by any scoring rule. The type parameter T names the element type: the parameter is T[], the scorer takes a T, and the result is T | undefined — undefined because the array may be empty. Each call gets its own T, inferred from the array you pass:
function maxBy<T>(items: T[], score: (item: T) => number): T | undefined {
let best: T | undefined;
for (const item of items) {
if (best === undefined || score(item) > score(best)) {
best = item;
}
}
return best;
}
console.log(maxBy([3, 41, 7], (n) => n));
console.log(maxBy(['css', 'typescript'], (s) => s.length));41
typescriptThe scorer parameter is where the checking happens: maxBy([3, 41, 7], (n) => n) infers T as number, so n is a number without an annotation, and a scorer that returned a string would be an error. Note the honest return type: T | undefined documents the empty case instead of hiding it behind a crash — and under noUncheckedIndexedAccess, indexing an array directly would give the same | undefined.
03. Constraining a generic with keyof
A generic that accepts any T can also be narrowed to some T. keyof T is the type of all property names of T — for Course, the union 'id' | 'title' | 'minutes'. Writing K extends keyof T as the constraint of a second type parameter says: the key you pass must be a real key of the object you pass. The indexed access type T[K] then names the type of that property, so the result keeps the exact element type:
interface Course {
id: string;
title: string;
minutes: number;
}
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const courses: Course[] = [
{ id: 'git-01', title: 'Git basics', minutes: 45 },
{ id: 'ts-01', title: 'TypeScript: first steps', minutes: 90 },
];
console.log(pluck(courses, 'title'));
console.log(pluck(courses, 'minutes'));[ 'Git basics', 'TypeScript: first steps' ]
[ 45, 90 ]pluck(courses, 'title') is typed string[] and pluck(courses, 'minutes') is number[] — one function, precise results. The constraint pays for itself the moment a key is misspelled or a field is renamed:
interface Course {
id: string;
title: string;
minutes: number;
}
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const courses: Course[] = [];
console.log(pluck(courses, 'titel'));pluck-mistake.ts(13,28): error TS2345: Argument of type '"titel"' is not
assignable to parameter of type 'keyof Course'.The untyped alternative, function pluck(items: any[], key: string), would accept the typo and return an array of undefined at runtime. Simply dropping extends keyof T does not even compile: T[K] is only valid when K is a key of T, so tsc reports TS2536: Type 'K' cannot be used to index type 'T'. This pattern — a constrained key plus an indexed access — is the backbone of typed data access: form field names, table columns and query parameters all benefit from the same shape. When you read a library whose functions know your object's fields, this is usually what it is built from.
04. Types built from values: as const and typeof
Types can also be derived — written once, computed from another type or value. Two operators do the deriving. typeof turns a value into its type, so a constant becomes the source of truth for everything that must match it. as const makes the value fully literal and readonly first, which is what makes the derived type precise:
const defaultTheme = { mode: 'dark', accent: 'teal' } as const;
type Theme = typeof defaultTheme;
// Theme is exactly:
// { readonly mode: 'dark'; readonly accent: 'teal' }
const theme: Theme = { mode: 'dark', accent: 'teal' };
console.log(theme.mode);darkNow the constant cannot drift from the type: edit defaultTheme and every value typed Theme fails to compile until it matches. This pairing is the idiomatic replacement for runtime lookup tables of names-to-values — the compiler checks the table and everything built on it.
05. Utility types: new types from old
TypeScript ships a set of utility types — small type-level functions that transform a type you have into the type you need. They read like the operations you already know from arrays and objects, applied to types:
interface Product {
id: string;
title: string;
price: number;
stock: number;
}
type Fields = keyof Product; // the four property names
type PriceTable = Record<string, number>;
type ProductDraft = Partial<Product>; // every field optional
type PublicProduct = Omit<Product, 'price' | 'stock'>;
type MakeProduct = (id: string) => Product;
type Made = ReturnType<MakeProduct>; // Product
const prices: PriceTable = { 'ts-01': 0, 'git-01': 12 };
const patch: ProductDraft = { price: 15 };
const visible: PublicProduct = {
id: 'ts-01',
title: 'TypeScript: first steps',
};
const made: Made = { id: 'x', title: 'T', price: 1, stock: 2 };
async function loadProduct(id: string): Promise<Product> {
return { id, title: 'Filled in later', price: 0, stock: 0 };
}
type LoadedProduct = Awaited<ReturnType<typeof loadProduct>>;
loadProduct('ts-01').then((p: LoadedProduct) => console.log(p.title));Filled in laterReading each one as a sentence makes them stick. Record<string, number> is "an object whose keys are strings and whose values are numbers" — a price table instead of one field per product. Partial<Product> is a patch or a form draft: every field present but optional, so { price: 15 } is a valid update payload. Omit<Product, 'price' | 'stock'> describes the same shape minus those two fields — a type for the public view of a product, and only a type (see the warning below). ReturnType<typeof loadProduct> names what a function returns, and wrapping it in Awaited looks through the Promise — so LoadedProduct is plain Product, the value you actually handle after awaiting. Their siblings work the same way: Pick selects named fields, Readonly forbids reassignment, Extract/Exclude/NonNullable carve up unions.
A type that describes a public view does not produce one. Types are erased when the code runs, and a full Product is assignable to PublicProduct because it has every field the smaller type needs (TypeScript only rejects extra fields in an object literal written in place). So a variable typed PublicProduct can still carry price and stock, and JSON.stringify sends them. To keep fields off the wire, build a new object that holds only the allowed ones:
interface Product {
id: string;
title: string;
price: number;
stock: number;
}
type PublicProduct = Omit<Product, 'price' | 'stock'>;
const product: Product = { id: 'ts-01', title: 'TS', price: 15, stock: 3 };
// Compiles: a Product has every field PublicProduct needs, plus extras.
const leaky: PublicProduct = product;
console.log('typed only:', JSON.stringify(leaky));
// A mapper builds a new object with only the public fields.
const toPublic = ({ id, title }: Product): PublicProduct => ({ id, title });
console.log('mapped: ', JSON.stringify(toPublic(product)));typed only: {"id":"ts-01","title":"TS","price":15,"stock":3}
mapped: {"id":"ts-01","title":"TS"}One level below the utilities sits the mechanism they are written with: mapped types. A mapped type walks over the keys of a type and rebuilds each field by a rule. Partial<T> is little more than { [K in keyof T]?: T[K] } — for every key in T, keep the key but make it optional. You can write your own with the same syntax:
interface Course {
id: string;
minutes: number;
}
// Every field becomes a string: a form that edits it as text.
type FormDraft<T> = {
[K in keyof T]: string;
};
const draft: FormDraft<Course> = { id: 'ts-01', minutes: '90 minutes' };
console.log(draft.minutes);90 minutesFormDraft<Course> has the same keys as Course but every field typed string, so the numeric 90 in place of '90 minutes' would be rejected. You rarely need to invent mapped types early on; what matters is reading them, because library docs and your own codebase will contain types such as Partial and friends — and now you know they are not magic, just a loop over keys.
06. Check your understanding
07. Apply it
Take a module from your own project with a hand-copied type and rebuild it from its source of truth: typeof a constant for a settings object, ReturnType on a fetch function for its response, Partial for the update payload, Omit to type the public view, plus a mapper that builds it, so fields the client may never see are never copied. Then write one generic — a pluck, a maxBy or a cache keyed by K extends string — and delete the copies it replaces. The skill practice for TypeScript Foundations ends with the same move: types derived from one source, so a shape change is a single edit plus a list of compiler errors telling you what to fix.
08. Review prompt
Without looking back: write the signature of a generic lastOf that returns the final element of an array or undefined. What does K extends keyof T prevent, and what does T[K] name? Match each of Partial, Pick, Omit, Record and ReturnType to a one-line description — then check yourself against the handbook list.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.