当前位置:网站首页>Typescript get function parameter type

Typescript get function parameter type

2022-07-06 22:33:00 User 6256742

Now there's a function update, We want to get its parameter type , What should you do ? At this time, we need to use Parameters

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

Get parameter type :

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

If you want to get state The type of ? You need to use infer

type GetType<T> = T extends (arg: infer P) => void ? P : string;
type StateType = GetType<typeof state>
//  StateType => any
//  because state No type set , therefore ts infer state The type of any

Translate this code : (arg: infer P):arg The type of is to be inferred as P The meaning of the whole code : If T Can be assigned to (arg: infer P) => void, Then return to P, Otherwise return to string

If you want to get the Return value type , Need to use typescript Built in methods provided ReturnType

type Return = ReturnType<typeof state>
// ReturnType => 
// {
//     router: any;
//}
原网站

版权声明
本文为[User 6256742]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061508095034.html