Course contentsShow
← TypeScript
Lesson 600 of 1,79614. Generics in PracticeFree lesson

Explicit Type Arguments with Angle Brackets

When and how to manually specify generic type parameters using angle bracket syntax.

Explicit Type Arguments with Angle Brackets

What You'll Learn

You'll learn when and how to manually specify generic type parameters using angle bracket syntax, giving you precise control over type inference.


When Inference Isn't Enough

TypeScript's generic inference is powerful, but it doesn't always guess what you want. Sometimes the compiler:

  • Picks a type that's too general (like unknown or a wide union)
  • Can't infer because there's no direct connection between arguments and type parameters
  • Needs explicit guidance to enforce stricter types

That's when explicit type arguments come in.


Angle Bracket Syntax

When calling a generic function, you can specify type parameters manually using angle brackets before the regular function arguments:

function identity<T>(value: T): T {
  return value;
}

// Inferred: T = number
const num = identity(42);

// Explicit: T = string
const str = identity<string>("hello");

// Force a specific type even if the value is more specific
const literal = identity<string>("exact"); // T = string, not "exact"

Think of it like giving TypeScript direct instructions instead of letting it guess.


Common Use Cases

Empty arrays:

function createArray<T>(): T[] {
  return [];
}

// Without explicit type, T = unknown
const items = createArray<number>(); // T = number

Forcing wider types:

const value = identity<number>(5); // T = number, not literal 5

Multiple type parameters:

function pair<A, B>(first: A, second: B): [A, B] {
  return [first, second];
}

const result = pair<string, boolean>("active", true);

Key Takeaway: Use angle brackets <T> immediately after the function name to explicitly provide type arguments when inference isn't specific enough or when working with functions that can't infer types from arguments alone.