Course contentsShow
← TypeScript
Lesson 862 of 1,79619. Template Literal TypesFree lesson

Catch-All and Optional Route Segments

Type routes with optional segments '/posts/[[...slug]]' to correctly infer parameter presence and type.

Catch-All and Optional Route Segments

What you'll learn: How to type routes with optional catch-all segments like /posts/[[...slug]] so TypeScript correctly infers when parameters may be present or completely absent.

Understanding the Challenge

In modern routing systems (especially Next.js), you'll encounter optional catch-all segments written as [[...slug]]. Unlike regular catch-all routes ([...slug]) which always capture segments, optional catch-alls can match the base route without any segments at all.

Think of it like a vacuum cleaner attachment: a catch-all route ([...slug]) is mandatory—you must attach something. An optional catch-all ([[...slug]]) means the vacuum works fine with or without the attachment.

The Type Inference Problem

When you have a route like /posts/[[...slug]], it matches:

  • /posts (no slug at all)
  • /posts/hello
  • /posts/hello/world

The tricky part: TypeScript needs to know that slug might be undefined entirely, not just an empty array.

Typing Optional Catch-Alls

With template literal types and conditional types, you can model this distinction:

type OptionalCatchAllRoute<T extends string> = T extends `${infer Base}/[[...${infer Param}]]`
  ? { base: Base; params?: string[] } // params is optional
  : never;

type PostRoute = OptionalCatchAllRoute<'/posts/[[...slug]]'>;
// Result: { base: '/posts'; params?: string[] }

The key difference from regular catch-alls: the ? on params makes the entire property optional, reflecting that the route matches even when no segments are provided.

Distinguishing Required vs Optional

You can build a type that handles both patterns:

type ParseCatchAll<T extends string> = 
  T extends `${infer Base}/[[...${infer Param}]]`
    ? { base: Base; params?: string[] }  // optional
    : T extends `${infer Base}/[...${infer Param}]`
    ? { base: Base; params: string[] }   // required
    : never;

type RequiredCatchAll = ParseCatchAll<'/api/[...path]'>;
// { base: '/api'; params: string[] }

type OptionalCatchAll = ParseCatchAll<'/posts/[[...slug]]'>;
// { base: '/posts'; params?: string[] }

This ensures your route handlers correctly handle cases where params might be entirely absent, not just empty.

Key Takeaway: Type optional catch-all segments with params?: string[] to reflect that the property itself may not exist, enabling type-safe routing for paths that work both with and without dynamic segments.