infer extends Constrains Captured Types

Use infer extends inside conditional types to capture tuple members as string or number literals, with a never fallback for mismatches.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
type FirstString<T extends readonly unknown[]> = T extends readonly [
  infer Head extends string,
  ...unknown[],
]
  ? Head
  : never;

type NumbersOnly<T extends readonly unknown[]> = T extends readonly [
  infer Head,
  ...infer Tail extends readonly unknown[],
]
  ? Head extends number
    ? [Head, ...NumbersOnly<Tail>]
    : NumbersOnly<Tail>
  : [];

type RouteParts = ['users', 42, 'posts', 7];
type First = FirstString<RouteParts>;
type Numbers = NumbersOnly<RouteParts>;

const first: First = 'users';
const numbers: Numbers = [42, 7];
console.log(first, numbers.join(','));

// infer extends 还能把宽泛成员收窄为字面量联合
type AsLiterals<T> = T extends readonly (infer Item extends string | number)[] ? Item : never;
const literal: AsLiterals<['a', 2, 'b']> = 2;
console.log('literal:', literal);

// 首项不是 string 时得到 never
type NoString = FirstString<[1, 2]>;
const blocked: NoString = undefined as never;
console.log('no string:', blocked === undefined);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

users 42,7
literal: 2
no string: true

Using it

The demo output is labeled (literal:, no string:), so each printed line maps back to the step that produced it.

Output is labeled for readability — expect lines prefixed with literal:, no string:.

Key statements

type AsLiterals<T> = T extends readonly (infer Item extends string | number)[] ? Item : never;

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced.