TypeScript: Returning a Conditional Type from a Generic Function over a Discriminated Union (TS2322)

TechLab Editorial TeamPublished 80 views1 answer
0

Editorial Q&A · This problem and its answer were written by the TechLab editorial team to document a common issue. It isn't a question from a community member. If you've hit a variation of it or know a better approach, add a reply below.

The problem

An event-processing service models its incoming events as a discriminated union on eventType. A generic enrichEvent function adds common metadata and applies type-specific changes to the payload. The goal is full type fidelity: passing a UserRegisteredEvent should return an EnrichedUserRegisteredEvent, so later code can use its specific fields without another type guard.

The return type is written as a conditional type over the input's eventType, and each branch of the function narrows on event.eventType before building its result. TypeScript rejects every return statement.

The code

TypeScript
// types.ts
interface BaseRawEvent {
  id: string;
  timestamp: string; // ISO string
}

interface UserRegisteredPayload {
  userId: string;
  email: string;
}

interface ProductViewedPayload {
  productId: string;
  category: string;
}

interface UserRegisteredEvent extends BaseRawEvent {
  eventType: 'USER_REGISTERED';
  payload: UserRegisteredPayload;
}

interface ProductViewedEvent extends BaseRawEvent {
  eventType: 'PRODUCT_VIEWED';
  payload: ProductViewedPayload;
}

type RawEvent = UserRegisteredEvent | ProductViewedEvent;

interface BaseEnrichedEvent {
  id: string;
  processedAt: Date;
  version: 1;
}

// Desired enriched types (manually defined for clarity of expectation)
interface EnrichedUserRegisteredEvent extends BaseEnrichedEvent {
  eventType: 'USER_REGISTERED';
  data: UserRegisteredPayload & { customUserField?: string };
}

interface EnrichedProductViewedEvent extends BaseEnrichedEvent {
  eventType: 'PRODUCT_VIEWED';
  data: ProductViewedPayload & { customProductField?: string };
}

// Our generic enriched event structure
type EnrichedEvent<T extends RawEvent['eventType']> = T extends 'USER_REGISTERED'
  ? EnrichedUserRegisteredEvent
  : T extends 'PRODUCT_VIEWED'
  ? EnrichedProductViewedEvent
  : never;

// eventProcessor.ts
function enrichEvent<T extends RawEvent>(event: T): EnrichedEvent<T['eventType']> {
  const commonFields = {
    id: event.id,
    processedAt: new Date(),
    version: 1 as const,
  };

  if (event.eventType === 'USER_REGISTERED') {
    const enrichedPayload: UserRegisteredPayload & { customUserField?: string } = {
      ...event.payload,
      customUserField: 'some_user_data', // specific enrichment
    };
    return {
      ...commonFields,
      eventType: event.eventType, // Expected: 'USER_REGISTERED'
      data: enrichedPayload,
    };
  } else if (event.eventType === 'PRODUCT_VIEWED') {
    const enrichedPayload: ProductViewedPayload & { customProductField?: string } = {
      ...event.payload,
      customProductField: 'some_product_data', // specific enrichment
    };
    return {
      ...commonFields,
      eventType: event.eventType, // Expected: 'PRODUCT_VIEWED'
      data: enrichedPayload,
    };
  }
  // This `else never` is implicitly handled by `T extends ... ? ... : never` in `EnrichedEvent`
  // but for the sake of completion, a real-world scenario might throw an error or handle unknown types.
  // For this problem, assume all `RawEvent` types are covered.
  throw new Error('Unknown event type');
}

// Usage
const userEvent: UserRegisteredEvent = {
  id: 'usr-123',
  timestamp: '2023-10-27T10:00:00Z',
  eventType: 'USER_REGISTERED',
  payload: { userId: 'abc', email: 'test@example.com' },
};

const enrichedUser = enrichEvent(userEvent);
enrichedUser.data.customUserField; // the goal: this should type-check

The error

Compiling with tsc --strict (TypeScript 5.9) reports both return statements:

Code
error TS2322: Type '{ eventType: "USER_REGISTERED"; data: UserRegisteredPayload & { customUserField?: string; }; id: string; processedAt: Date; version: 1; }' is not assignable to type 'EnrichedEvent<T["eventType"]>'.
error TS2322: Type '{ eventType: "PRODUCT_VIEWED"; data: ProductViewedPayload & { customProductField?: string; }; id: string; processedAt: Date; version: 1; }' is not assignable to type 'EnrichedEvent<T["eventType"]>'.

Adding as EnrichedUserRegisteredEvent to each returned object doesn't help either: the error just becomes Type 'EnrichedUserRegisteredEvent' is not assignable to type 'EnrichedEvent<T["eventType"]>'.

The question: why doesn't narrowing event.eventType satisfy the conditional return type, and how should a function like this be typed?

Advertisement

1 Answer

0

Why it happens

The callers are fine. enrichEvent(userEvent) infers T = UserRegisteredEvent, so the declared return type resolves to EnrichedUserRegisteredEvent. The problem is entirely inside the function body.

Inside the function, T is still an unresolved type parameter. if (event.eventType === 'USER_REGISTERED') narrows the value event, but TypeScript doesn't narrow the type parameter T from that check. (It can't in general: T could be instantiated with the whole union, or with a subtype.) So in each branch the declared return type is still EnrichedEvent<T['eventType']>, a conditional type TypeScript can't evaluate until T is known. It treats that as opaque, and no concrete object type is assignable to it, which is why even an assertion to the specific enriched type fails.

This is a known limitation, usually called the "correlated union" problem. The fixes below all type-check under tsc --strict (verified with TypeScript 5.9).

Describe the input-to-output mapping with overload signatures and implement it once against the plain union. Inside the implementation, ordinary narrowing works, and the compiler checks each branch's return value for real:

TypeScript
function enrichEvent(event: UserRegisteredEvent): EnrichedUserRegisteredEvent;
function enrichEvent(event: ProductViewedEvent): EnrichedProductViewedEvent;
function enrichEvent(event: RawEvent): EnrichedUserRegisteredEvent | EnrichedProductViewedEvent;
function enrichEvent(event: RawEvent): EnrichedUserRegisteredEvent | EnrichedProductViewedEvent {
  const common = { id: event.id, processedAt: new Date(), version: 1 as const };

  switch (event.eventType) {
    case 'USER_REGISTERED':
      return { ...common, eventType: event.eventType, data: { ...event.payload, customUserField: 'some_user_data' } };
    case 'PRODUCT_VIEWED':
      return { ...common, eventType: event.eventType, data: { ...event.payload, customProductField: 'some_product_data' } };
    default: {
      const unhandled: never = event;
      throw new Error(`Unhandled event type: ${JSON.stringify(unhandled)}`);
    }
  }
}

Callers get the precise type: enrichEvent(userEvent).data.customUserField compiles, and passing a value typed as the full RawEvent union returns the union of enriched types. The never check in default makes adding a new event type without a branch a compile error. The cost is one overload line per event type.

Option 2: Keep the generic signature, cast once

If you want to keep EnrichedEvent<T['eventType']>, do the narrowing on a variable typed as the concrete union, build a result typed as the union of outputs, and cast to the declared return type once at the end:

TypeScript
function enrichEvent<T extends RawEvent>(event: T): EnrichedEvent<T['eventType']> {
  const e: RawEvent = event; // narrowing works on the concrete union, not on T
  const common = { id: e.id, processedAt: new Date(), version: 1 as const };
  let result: EnrichedUserRegisteredEvent | EnrichedProductViewedEvent;
  switch (e.eventType) {
    case 'USER_REGISTERED':
      result = { ...common, eventType: e.eventType, data: { ...e.payload, customUserField: 'x' } };
      break;
    case 'PRODUCT_VIEWED':
      result = { ...common, eventType: e.eventType, data: { ...e.payload, customProductField: 'y' } };
      break;
    default: {
      const unhandled: never = e;
      throw new Error(`Unhandled event type: ${JSON.stringify(unhandled)}`);
    }
  }
  return result as EnrichedEvent<T['eventType']>;
}

The cast is to EnrichedEvent<T['eventType']>, the declared return type, not to a specific branch type. That's the only assertion TypeScript accepts here, and it's unchecked: TypeScript won't notice if a branch returns the wrong variant. Option 1 avoids that.

Option 3: A lookup map for many event types

With many event types, overloads get long. Since TypeScript 4.6, describing the events as a map from type to payload lets the compiler correlate input and output through an indexed access type, with no casts at all:

TypeScript
interface PayloadMap { USER_REGISTERED: UserRegisteredPayload; PRODUCT_VIEWED: ProductViewedPayload; }
interface EnrichedDataMap {
  USER_REGISTERED: UserRegisteredPayload & { customUserField?: string };
  PRODUCT_VIEWED: ProductViewedPayload & { customProductField?: string };
}
type EventType = keyof PayloadMap;
type RawEventOf<K extends EventType> = { [P in K]: BaseRawEvent & { eventType: P; payload: PayloadMap[P] } }[K];
type EnrichedOf<K extends EventType> = { [P in K]: BaseEnrichedEvent & { eventType: P; data: EnrichedDataMap[P] } }[K];

const enrichData: { [K in EventType]: (payload: PayloadMap[K]) => EnrichedDataMap[K] } = {
  USER_REGISTERED: (payload) => ({ ...payload, customUserField: 'some_user_data' }),
  PRODUCT_VIEWED: (payload) => ({ ...payload, customProductField: 'some_product_data' }),
};

function enrichEvent<K extends EventType>(event: RawEventOf<K>): EnrichedOf<K> {
  const enrich: (payload: PayloadMap[K]) => EnrichedDataMap[K] = enrichData[event.eventType];
  return { id: event.id, processedAt: new Date(), version: 1, eventType: event.eventType, data: enrich(event.payload) };
}

Each enricher is checked against its own payload and output type. Adding an event type means adding one entry to each map, and forgetting the enrichData entry is a compile error.

  1. Exhaustiveness: the const unhandled: never = event check only works on a variable of the concrete union type (as in options 1 and 2). On a value of generic type T, TypeScript doesn't narrow far enough to reach never.
  2. as any and as unknown as X: these silence the error but also switch off checking of the returned object entirely. Prefer the overloads or the lookup map, where the compiler still verifies each branch.

💡 Bonus Tip: Validate Events at the Boundary

Events arriving over HTTP or from a queue are unknown until checked. Parse them with a schema library such as Zod using a discriminated union (z.discriminatedUnion('eventType', [...])), and infer RawEvent from the schema. The union type and the runtime validation then can't drift apart, and enrichEvent only ever receives events that really match their declared type.

TechLab Editorial TeamAuthorAnswered

Know the answer?

Posting answers needs a TechLab plan. Reading every discussion stays free.