You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript场景下能否将ofType函数返回结果正确推断为boolean类型?

Can 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):

  1. TypeScript infers the generic T as ActionWithPayload<one.foo, boolean>—this is the only action type in your action union that matches the one.foo type string.
  2. The rest parameter param is typed as T["type"][], which resolves to one.foo[], so passing one.foo is valid.
  3. The return type condition checks if T extends ActionWithPayload<typeof param[number], infer U>. Since typeof param[number] is one.foo, T exactly matches this structure, so TypeScript infers U as boolean. The return type becomes boolean.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:11:45