美文网首页
typescript获取函数的参数类型

typescript获取函数的参数类型

作者: DSuperLu | 来源:发表于2020-09-28 20:32 被阅读0次

    现在有一个函数update,我们想要获取他的参数类型,你应该怎么做呢?这个时候我们需要就要用到Parameters

    function updata(state) {
        return {
            router: state.router
        }
    }
    

    获取参数类型:

    type ArrType = Parameters<typeof updata>
    // ArrType => [state: any]
    

    如果想获取state的类型呢?这个时候需要用到infer

    type GetType<T> = T extends (arg: infer P) => void ? P : string;
    type StateType = GetType<typeof update>
    //  StateType => any
    // 因为state没有设置类型,所以ts推断state的类型为any
    

    把这段代码翻译一下:
    (arg: infer P):arg的类型待推断为P
    整段代码的意思:如果T能赋值给(arg: infer P) => void,则返回P,否则返回string

    如果想要获取函数的返回值类型,需要使用typescript提供的内置方法ReturnType

    type Return = ReturnType<typeof update>
    // ReturnType => 
    // {
    //     router: any;
    //}
    

    相关文章

      网友评论

          本文标题:typescript获取函数的参数类型

          本文链接:https://www.haomeiwen.com/subject/hpdjuktx.html