Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Generic Constraints | TypeScript Mastery lesson | BraveProgrammer
  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 10 of 56

·Typescript

Generic Constraints

25 minutes

Course progress18%

Constraining Generics with extends

interface Lengthwise { length: number; }

function logLength<T extends Lengthwise>(arg: T): void {
  console.(arg.);
}

([, , ]); 
();   

log
length
logLength
1
2
3
// OK – arrays have length
logLength
"hello"
// OK – string has length
// logLength(123); // ❌ number doesn't have length

Using keyof to constrain property names

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

const person = { name: "Bob", age: 30 };
const name = getProp(person, "name"); // inferred as string

Conditional Types with Generics

type NonNullable<T> = T extends null | undefined ? never : T;
type NN = NonNullable<string | undefined>; // string

Info

Combine constraints with utility types (Partial, Pick) for powerful type transformations.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from TypeScript MasteryBrowse activities
Previous lessonGenerics – BasicsContinue to lesson 11Mapped Types & `keyof`Back to TypeScript Mastery curriculum