小编wwo*_*ers的帖子

为什么我收到“类型实例化过深并且可能是无限的”?

游乐场链接

我有这些一般定义:

type Module<P extends Payloads, C extends Children> = {
    payloads: P;
    children: C;
};

type Children = Record<string, any>; // some values will be nested Modules

type Payloads = Record<string, any>;

type ExtractPayloads<M extends Module<any, any>> = M extends Module<infer P, any> ? P : never;

type ExtractChildren<M extends Module<any, any>> = M extends Module<any, infer C> ? C : never;
Run Code Online (Sandbox Code Playgroud)

基本上,模块是指定类型的类型children,可以包含嵌套模块。

我有这种类型,可以Action根据模块的payload类型生成 s:

type ModuleRootActions<
  MODULE extends Module<any, any>,
  PAYLOADS = …
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics

14
推荐指数
3
解决办法
3万
查看次数

如何避免分布式条件类型

这些是我有的类型:

type Action<T> = T extends undefined ? {
    type: string;
} : {
    type: string;
    payload: T;
}

type ApiResponse<T> = {
    ok: false;
    error: string;
} | {
    ok: true;
    data: T;
};
Run Code Online (Sandbox Code Playgroud)

我定义了这个函数:

function handleApiResponse<T>(apiResponse: ApiResponse<T>) {
    const a: Action<ApiResponse<T>> = {
        type: "response",
        payload: apiResponse,
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是a有错误,因为 中的条件类型Action分布在 上ApiResponse

我需要的Action<T>是一种顾名思义的类型,即有两种情况:

  1. 传递给的类型参数Action<T>未定义,在这种情况下Action<undefined>={ type: string }
  2. 传递给的类型参数Action<T>是其他任何东西,在这种情况下Action<T>={ type: string, …

typescript

3
推荐指数
1
解决办法
864
查看次数

标签 统计

typescript ×2

typescript-generics ×1