TypeScript场景下能否将ofType函数返回结果正确推断为boolean类型?
ofType Infer the Return Type as boolean? Yes, when you call ofType(one.foo), TypeScript will correctly infer the return type as boolean. Let’s break down why this works, along with a limitation in the current implementation and how to fix it.
Why It Works for Single Action Types
Let’s walk through the type inference step-by-step when calling ofType(one.foo):
- TypeScript infers the generic
TasActionWithPayload<one.foo, boolean>—this is the only action type in youractionunion that matches theone.footype string. - The rest parameter
paramis typed asT["type"][], which resolves toone.foo[], so passingone.foois valid. - The return type condition checks if
TextendsActionWithPayload<typeof param[number], infer U>. Sincetypeof param[number]isone.foo,Texactly matches this structure, so TypeScript infersUasboolean. The return type becomesboolean.
Limitation: Multiple Action Types
The current implementation falls short when passing multiple action types (e.g., ofType(one.foo, one.bar)). In this case, TypeScript will infer the return type as never instead of boolean | string. This happens because the union action doesn’t extend ActionWithPayload<one.foo | one.bar, U>—there’s no single U that can cover both boolean and string payloads.
Improved Implementation
To handle both single and multiple action types correctly, adjust the ofType function to use Extract to target relevant action types from the union:
interface ActionWithPayload<T extends string, K> { type: T, payload: K } enum one { foo = "foo", bar = "bar" } type action = ActionWithPayload<one.foo, boolean> | ActionWithPayload<one.bar, string>; function ofType<T extends action["type"]>(...types: T[]): Extract<action, { type: T }>["payload"] { return null as any; // Runtime implementation can be adjusted as needed } // Usage examples: const fooResult = ofType(one.foo); // Type: boolean const barResult = ofType(one.bar); // Type: string const combinedResult = ofType(one.foo, one.bar); // Type: boolean | string
This version uses Extract to pick the subset of action types that match the passed type strings, then extracts their payload types. It correctly infers union payloads when multiple types are provided.
内容的提问来源于stack exchange,提问作者MichaelAttard

