Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Dev

TypeScript Advanced Types: Generics, Conditional & Template Literal Types

By: Md Tarek · 17 Oct 2026

TypeScript advanced type system with generics and conditional types
TypeScript advanced type system with generics and conditional types

Executive Summary & Key Takeaways

  • Generics make a function's type depend on its input — function identity<T>(x: T): T — preserving the exact type instead of collapsing to any or a union.
  • Conditional types are type-level if/else: T extends U ? X : Y, the building block for utilities like Exclude, Extract, and ReturnType.
  • The `infer` keyword captures types inside another type — T extends Promise<infer R> ? R : never unwraps a promise's resolved type.
  • Template literal types build string unions (${Prefix}-${Suffix}) and power things like typed event names and URL routes.
  • Mapped types transform object shapes ({ [K in keyof T]: ... }) with as key remapping and -? / +? modifiers.

1. Generics That Preserve Types

Without generics, a function that returns the first element of an array loses the element type. With a generic, the return type flows from the argument:

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}
const n = first([1, 2, 3]); // n: number | undefined

2. Conditional Types and infer

Conditional types distribute over unions, which is why Exclude and Extract work the way they do. The infer keyword lets you reach inside a type:

type Unwrap<T> = T extends Promise<infer R> ? R : T;
type A = Unwrap<Promise<string>>; // string

3. Template Literal Types

These are surprisingly useful for API design. A typed event system can derive handler names from the event union:

type Event = 'user.created' | 'user.deleted';
type Handler = `on${Capitalize<Event>}`; // 'onUser.created' | 'onUser.deleted'

| Utility | What it does | Example | |---|---|---| | Partial<T> | all props optional | Partial<{a: number}> => {a?: number} | | Required<T> | all props required | Required<{a?: number}> => {a: number} | | Pick / Omit | select / drop keys | Omit<T, 'id'> | | ReturnType | function return type | ReturnType<typeof fn> | | Awaited | resolved promise type | Awaited<Promise<string>> => string |

4. When to Reach for Advanced Types

Advanced types shine at the edges of your codebase — library boundaries, API clients, and configuration objects — where you want compile-time guarantees. In the middle of application code, prefer simple interfaces and explicit types: advanced types should make the API safer, not make the code harder to read.

FAQ

Are conditional types slow? Complex recursive conditional types can slow the compiler, but for normal use the cost is negligible. If a type gets pathological, simplify it or add an explicit annotation.