TypeScript Foundations·Types that pay for themselves

Generics that stay readable

Write one typed function for many value types without losing safety.

Intermediate 15 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Use T for a value type and K extends keyof T for property keys.
  • Partial, Pick, Omit and Record are built-in transformations.
  • If a generic is used once and unconstrained, a concrete type is usually clearer.

In plain English

A generic is a type parameter. It lets a function preserve the relationship between an input and an output. Constraints narrow what the parameter can be, while utility types derive new shapes from existing ones.

collections.tsTypeScript
function first<T>(items: T[]): T | undefined {
  return items[0]
}

function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find((item) => item.id === id)
}

const score = first([88, 91, 74])
const lesson = byId([{ id: 'html', title: 'HTML' }], 'html')
Your turn

Build a typed picker

Medium

Write pick<T, K extends keyof T>(items: T[], key: K): T[K][] that extracts one property from each item.

TS · starter
function pick(items, key) {
  return []
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does K extends keyof T guarantee?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course