[英]In TypeScript, how do i type a function's arguments but not the return value?
I am writing an application using redux, redux-thunk and reselect in TypeScript. 我正在使用Redux,redux-thunk和在TypeScript中重新选择编写应用程序。
In many places, i am writing functions like this: 在许多地方,我正在编写如下函数:
const selectThing = (store: IStore) => store.path.to.thing;
const fetchThing = (thingId: string) => (dispatch: Dispatch<IStore>, getState: () => IStore) => {
// fetch a thing by id and handle the result
return result;
}
Especially in the second example, the typing annotations for the second function take up much space and i would like to write a function interface which handles typing the arguments. 尤其是在第二个示例中,第二个函数的类型注释会占用很多空间,我想编写一个处理参数类型的函数接口。
type StoreSelector<T = any> = (store: IStore) => T;
type ThunkDispatch<T = any> = (dispatch: Dispatch<IStore>, getState: () => IStore) => T;
The typings above solve the issue of manually having to type the parameters each time, but they will require me to manually type the return value of the functions, which worked automatically before. 上面的键入解决了每次都必须手动键入参数的问题,但是它们将要求我手动键入函数的返回值,该函数以前会自动工作。
Is there a way to type a function's arguments, but let typescript then automatically detect the return value of the function body? 有没有办法键入函数的参数,但是让Typescript然后自动检测函数体的返回值?
You can use a function to get inference for the return type and inference for the parameter types. 您可以使用函数来获取返回类型的推论和参数类型的推论。
function createThunkDispatch<T>(fn: (dispatch: Dispatch<IStore>, getState: () => IStore) => T) {
return fn;
}
// const fetchThing: (thingId: string) => (dispatch: Dispatch<IStore>, getState: () => IStore) => string
const fetchThing = (thingId: string) => createThunkDispatch((dispatch, getState) => {
// fetch a thing by id and handle the result
return "result";
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.