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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 10 of 56 · Typescript

Generic Constraints

Duration: 25 minutes

Constraining Generics with extends

interface Lengthwise { length: number; }

function logLength<T extends Lengthwise>(arg: T): void {
  console.log(arg.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.

Previous: Generics – BasicsNext: Mapped Types & `keyof`