有没有办法在打字稿中合并不确定数量的函数的返回类型?

sample code  既然创建者包含不确定数量的功能,有没有办法做到这一点?

    const show = () => ({ type: "show" });
    const setText = (text: string) => ({ type: "setText",payload: { text } });

    const creators = {
        show,setText
    }

    type actionCreators<T> = T[keyof T] extends (...args: any[]) => infer R ? R : never;

    type A = actionCreators<typeof creators>;
    // A = { type : string }
    // expect A to be { type : string,payload : { text : string } }
    // Is there a way to do that,since creators consist of an uncertain numbers of functions?
zkl829602 回答:有没有办法在打字稿中合并不确定数量的函数的返回类型?

我不太确定您所说的“合并”是什么意思。您得到的是方法返回类型的union。也许您想要intersection代替?您可以使用conditional type trick来合成数量未知的交集。在这里,它适用于提取方法返回类型:

type IntersectionOfMethodReturnTypes<T> = {
    [K in keyof T]: (x: T[K] extends (...args: any) => infer R ? R : unknown) => void
}[keyof T] extends ((x: infer R) => void) ? R : never;

产生

type A = IntersectionOfMethodReturnTypes<typeof creators>
/*
type A = {
    type: string;
} & {
    type: string;
    payload: {
        text: string;
    };
}
*/

相当于您想要的。如果希望它看起来像单一对象类型,则可以稍微更改类型别名定义:

type IntersectionOfMethodReturnTypes<T> = {
    [K in keyof T]: (x: T[K] extends (...args: any) => infer R ? R : unknown) => void
}[keyof T] extends ((x: infer R) => void) ? { [K in keyof R]: R[K] } : never;

产生

/*
type A = {
    type: string;
    payload: {
        text: string;
    };
}
*/

这符合我认为在类型级别上的要求;它是否代表您实际产生或处理的值的类型取决于您的实现。

好的,希望能有所帮助;祝你好运!

Link to code

本文链接:https://www.f2er.com/3116676.html

大家都在问