如何从泛型函数获取赋值返回类型

时间:2019-11-17 23:46:01

标签: typescript

class Dyn {
    static flatten (a: any) {

    }
    static cliff <G extends any[], B, A extends (...a: G) => B, Z>(a: A, b: ( ) => Z) {
        return (...p: G) => { 
            const runA = a(...p)
            return {
                _: runA,
                ...b()
            }
        }
    }
}

type User = { name: string, id: number }
type Kitten = { name: string, id: number }
const getUserById = (id: number): User => ({ name: 'thomas', id })
const getKittenById = (id: number): Kitten => ({ name: 'thomas', id})


const x = Dyn.flatten({
    user: Dyn.cliff(getUserById, () => ({
        kitten: getKittenById
    }))
})

Playground

我试图理解为什么将鼠标悬停在Dyn.cliff上。

(method) Dyn.cliff<any[], unknown, (id: number) => User, {
    kitten: (id: number) => Kitten;
}>(a: (id: number) => User, b: () => {
    kitten: (id: number) => Kitten;
}): (...p: any[]) => {
    _: unknown;
} & {
    kitten: (id: number) => Kitten;
}

我如何拥有它,以便_: unknown;我们_: User

1 个答案:

答案 0 :(得分:1)

正如jcalz在评论中提到的那样,删除额外的类型参数可以提供更好的推断。在这种情况下,您需要删除多余的类型参数,并使用Parameters<T>ReturnType<T>助手来获取所需的类型。 Playground

class Dyn {
    static flatten (a: any) {

    }
    static cliff<A extends (...a: any[]) => any, Z>(a: A, b: ( ) => Z) {
        return (...p: Parameters<A>) => {
            // Without the explicit type declaration here runA is determined to be `any`
            // before the generic is resolved.
            const runA: ReturnType<A> = a(...p)
            return {
                _: runA,
                ...b()
            }
        }
    }
}

type User = { name: string, id: number }
type Kitten = { name: string, id: number }
const getUserById = (id: number): User => ({ name: 'thomas', id })
const getKittenById = (id: number): Kitten => ({ name: 'thomas', id})


const x = Dyn.flatten({
    user: Dyn.cliff(getUserById, () => ({
        kitten: getKittenById
    }))
})