如何使用Redux类型将返回类型转换为void?

时间:2019-05-26 12:15:43

标签: typescript redux react-redux

我想根据动作类型派生道具的类型。由于动作类型总是返回动作对象,而派遣的道具没有返回类型,我们如何才能像预期类型那样获得正确的派遣道具类型?

export type Action =
  ({ type: 'PING', arg: number })

const ping = (arg: number): Action => ({
  type: 'PING', arg
})

interface Props {
  ping: typeof ping;
}

const PingTestComponent: React.SFC<Props> = ({ping}) => {
  return (
    <Button onPress={() => ping(123)} title="ping"/>
  );
};

export const PingTest = connect(
  null,
  ({ ping: ping })
)(PingTestComponent);

我期望派遣的道具解析类型为

期望

 interface Props {
   ping: (arg: number) => void
}

1 个答案:

答案 0 :(得分:0)

实际上,连接到动作创建者的道具将具有相同的返回类型,而不是void

无论如何,这是您可以更改函数的返回类型的方法:

declare function foo(bar: string, baz: boolean): { type: 'A' };

type WithReturnVoid<T extends (...arg) => any> = (...args: Parameters<T>) => void;

type VoidFoo = WithReturnVoid<typeof foo>; // (bar: string, baz: boolean) => void

Playground

Parameters是内置实用程序,允许获取函数参数的类型。

因此在您的示例中将是:

interface Props {
  ping: WithReturnVoid<typeof ping>;
}
相关问题