我有这些一般定义:
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) 这些是我有的类型:
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>是一种顾名思义的类型,即有两种情况:
Action<T>未定义,在这种情况下Action<undefined>={ type: string }Action<T>是其他任何东西,在这种情况下Action<T>={ type: string, …