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
// 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-checkThe error
Compiling with tsc --strict (TypeScript 5.9) reports both return statements:
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?
